Bernie Lenz
Bernie Lenz

Reputation: 2146

XPath/JSONPath search of arrays

Our REST API is returning an array of nested objects. Using XPath or JSONPath, I would like to extract the id elements of each top level array object but not the children's id elements.

[
   {
      "id":"1",
      "child":{
         "id":"a"
      }
   },
   {
      "id":"2",
      "child":{
         "id":"b"
      }
   }
]

The expected output is 1, 2 and NOT 1, a, 2, b.

Can anybody help with the query syntax? I have the example at http://jsfiddle.net/dqvrfvc1/2/

Upvotes: 0

Views: 1626

Answers (3)

Michael Kay
Michael Kay

Reputation: 163595

You mentioned XPath: in XPath 3.1 this is

parse-json($data)?*?id

Upvotes: 1

Dmitri T
Dmitri T

Reputation: 168157

Given you have jmeter in your tags here is a solution for it:

JSON Path Expression should look like: $[*].id

Demo:

JMeter JSON Path Extractor Demo

References:

Upvotes: 1

Daniel Haley
Daniel Haley

Reputation: 52888

Try selecting the id at a specific level:

search = JSON.search(data, '/*/*/id')

See the update here: http://jsfiddle.net/dqvrfvc1/5/

If we dump the XML to the console (console.log(JSON.toXML(data));) we see:

<d:data xmlns:d="defiant-namespace" d:constr="Array" d:mi="9">
    <d:item d:mi="4">
        <id d:constr="String" d:mi="1">1</id>
        <child d:mi="3">
            <id d:constr="String" d:mi="2">a</id>
        </child>
    </d:item>
    <d:item d:mi="8">
        <id d:constr="String" d:mi="5">2</id>
        <child d:mi="7">
            <id d:constr="String" d:mi="6">b</id>
        </child>
    </d:item>
</d:data>

This means that instead of /*/*/id, we can be even more specific with:

search = JSON.search(data, '/d:data/d:item/id')

Note: Namespace selection isn't possible, so there doesn't seem to be the need to bind the d: namespace prefix to the defiant-namespace uri.

Also, take a look at the "XPATH EVALUATOR" section of http://defiantjs.com and switch between XML and JSON views to see how the JSON is represented in XML. This will help you understand the the data structure and at what level id would be found.

Upvotes: 2

Related Questions