1

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?

wp78de
  • 18,207
  • 7
  • 43
  • 71
Drex
  • 3,346
  • 9
  • 33
  • 58
  • 1
    The closest query I got was `$.items[*][?(@.album.meta[0].name=="CreatedBy" && @.album.meta[0].value=="Karen")]['id','name']`. Works Only if the CreatedBy is at the same index position in every metadata. Tried with Jayway JsonPath Implementation. https://jsonpath.herokuapp.com/. May not work with other implementations – Akshay G Oct 07 '21 at 09:08
  • That actually looks good, thank you very much! – Drex Oct 07 '21 at 16:17

1 Answers1

1

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

Akshay G
  • 2,070
  • 1
  • 15
  • 33