Drex
Drex

Reputation: 3831

Jsonpath to grab parent field info with condition on child field

We can use jsonpath to select values for given expressions, for the following example and question:

{
   "items": [
   {
      "id": 1,
      "name": "item1",
      "album": {
         "name": "Summer Trip",
         "meta": [
            {
             "name": "CreatedBy",
             "value": "Karen"
            },
            {
             "name": "Address",
             "value": "San Jose, CA"
            }
         ]
      }
   },
   {
      "id": 2,
      "name": "item2",
      "album": {
         "name": "Winter Trip",
         "meta": [
            {
             "name": "CreatedBy",
             "value": "Lola"
            },
            {
             "name": "Address",
             "value": "Seattle, WA"
            }
         ]
      }
   }

   ] 
}

I would like to filter out items that its album's meta with condition as name == "CreatedBy" and value == "Karen", and return the item id and name. For example:

{
   items: [
      {
         "id": 1,
         "name": "item1"
      }
   ]
}

By looking at how jsonpath works, it seems once you go deeper into nested JSON nodes, it's not able to catch the parent node value, for example, I can catch node values like

$..meta[?(@.name == 'CreatedBy' && @.value == "Karen")]

which returned me with the object inside meta, rather than its parent node items.

[
  {
     "name": "CreatedBy",
     "value": "Karen"
  }
]

Is it possible to use jsonpath to achieve what I am looking for?

Upvotes: 1

Views: 3096

Answers (1)

Akshay G
Akshay G

Reputation: 2280

If you are using Jayway JSONPath you can use filter operators.

contains filter operator

$.items[?(@.album.meta[?(@.name=='CreatedBy')].value contains 'Karen')]['id','name']

in filter operator

$.items[?('Karen' in @.album.meta[?(@.name=='CreatedBy')].value)]['id','name']

Fixed index position

$.items[*][?(@.album.meta[0].name=="CreatedBy" && @.album.meta[0].value=="Karen")]['id','name']

Online Test Tool : Jayway JsonPath Evaluator

Upvotes: 1

Related Questions