Forum Discussion

SiKing's avatar
SiKing
Community Expert
8 years ago

context.expand produces different results between JSON and XML

I have some JSON response from a service, like:

{ "foo": "bar" }

I try to read this from a Groovy step, like:

log.info context.expand('${REST Request#Response#$..foo}')
log.info context.expand('${REST Request#ResponseAsXml#//*:foo}')

In my log is get:

INFO: [bar]
INFO: bar

Why the extra square brackets in the first case?

  • Either JSONpath expression $.foo (single dot) or $..foo[0] (the first occurrence in an array) would return a string.

  • nmrao's avatar
    nmrao
    Champion Level 3

    I am not really good at json path.

     

    From this page,

    $..foo => reads all the property keys with foo from json,  returns a array / list always irrespective of count and as you know list in groovy is represented between [..]

  • PaulMS's avatar
    PaulMS
    Super Contributor

    Either JSONpath expression $.foo (single dot) or $..foo[0] (the first occurrence in an array) would return a string.

    • SiKing's avatar
      SiKing
      Community Expert

      The XPath //*:foo can also return multiple results. I was just hoping they both would behave consistently. Also, returning an array notation as a single string is iffy.

       

      But thanx for the answer.

      • nmrao's avatar
        nmrao
        Champion Level 3

        May be below would be helpful if it needs to be dynamic.

         

  • SiKing's avatar
    SiKing
    Community Expert

    Maybe another way to look at it:

    Because the $..foo notation always adds the square brackets, if you use the JSONPath Existence Assertion, looking for $..anything will be true regardless of whether the node is present or not. This is clearly a bug.