William Boman
William Boman

Reputation: 2227

Using JSONPath to find an object based on one of its properties

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[[email protected][?(@.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?

Upvotes: 1

Views: 5037

Answers (1)

evilmandarine
evilmandarine

Reputation: 4553

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/

Upvotes: 2

Related Questions