Extract values from web service JSON response with JSONPath

495 views Asked by At

I have a JSON response from web service that looks something like this :

[
   {
      "id":4,
      "sourceID":null,
      "subject":"SomeSubjectOne",
      "category":"SomeCategoryTwo",
      "impact":null,
      "status":"completed"  
   },
   {
      "id":12,
      "sourceID":null,
      "subject":"SomeSubjectTwo",
      "category":"SomeCategoryTwo",
      "impact":null,
      "status":"assigned"
   }
]

What I need to do is extract the subjects from all of the entities by using JSONPATH query.

How can I get these results :

  1. Subject from the first item - SomeSubjectOne
  2. Filter on specific subject value from all entities (SomeSubjectTwo for example)
  3. Get Subjects from all entities
1

There are 1 answers

0
wp78de On

Goessner's orinial JSONPath article is a good reference point and all implementations more or less stick to the suggested query syntax. However, implementations like Jayway JsonPath/Java, JSONPath-Plus/JavaScript, flow-jsonpath/PHP may behave a little differently in some areas. That's why it can be important to know what implementation you are actually using.

  1. Subject from the first item

    Just use an index to select the desired array element.

    $.[0].subject
    

    Returns:

SomeSubjectOne

  1. Specific subject value

    First, go for any elements .., check those with a subject [?(@.subject] and use == '..' for comparison.

    $..[?(@.subject == 'SomeSubjectTwo')]
    

Returns

[ { "id" : 12, "sourceID" : null, "subject" : "SomeSubjectTwo", "category" : "SomeCategoryTwo", "impact" : null, "status" : "assigned" } ]*

  1. Get all subjects

    $.[*].subject
    

    or simply

    $..subject
    

Returns

[ "SomeSubjectOne", "SomeSubjectTwo" ]