0

Given the following JSON structure, I want to be able to find the entry in the $.data array that contains an item with a specific itemId.

{
  "data": [
    {
      "id": "1",
      "items": [{"itemId": "item1"}]
    },
    {
      "id": "2",
      "items": [{"itemId": "item2"}]
    }
  ]
}

Let's say I'm looking for the entry with an itemId == "item2" - in which case I want to extract the full object:

{
  "id": "2",
  "items": [{"itemId": "item2"}]
}

I've attempted nesting $() filters, but to no avail:

$.data[?@.items[?(@.itemId == "item2")])]
$.data[?("item2" in @.items[*].itemId)]
$.data[?(@.items[*].itemId contains "item2")]

I can easily find the "item" object itself, through $.data[*].items[?(@.itemId == "item2")], but I'd like to actually retrieve its parent object! Is this even possible with JSONPath?

William Boman
  • 2,079
  • 5
  • 26
  • 39
  • [Jayway JSONPath (A Java DSL)](https://github.com/json-path/JsonPath#filter-operators) supports additional filter operator like `in` and `contains`. Try here https://jsonpath.herokuapp.com/ – Akshay G Feb 03 '22 at 04:56
  • Which library/implementation of JSONPath are you using? – Akshay G Feb 03 '22 at 04:59

1 Answers1

1

In this specific example, this should work:

$..data[?(@.items[0].itemId == 'item2')]

Result is a list, because filters always return lists:

[
  {
    "id": "2",
    "items": [
      {
        "itemId": "item2"
      }
    ]
  }
]

This works here because we're taking the first element in the items array in order to apply the filter (index [0]). For a more complex scenario, some tweaking may be needed.

Tested here: https://jsonpath.com/

evilmandarine
  • 4,241
  • 4
  • 17
  • 40