Search code examples
jsonjsonpathjayway

Jsonpath: get the value of an element based on its sibling, when the sibiling element is an array containing a specific value


With the following json:

{
  "elements": [
    {
      "ids": [
        {
          "id": "A"
        },
        {
          "id": "B"
        }
      ],
      "value": "one"
    },
    {
      "ids": [
        {
          "id": "C"
        },
        {
          "id": "D"
        }
      ],
      "value": "two"
    }
  ]
}

What would be the jsonpath to return the value one when asking for the id A?

As per https://stackoverflow.com/a/47576707 I can retrieve the ids element containing A:

$.elements.*.ids[?(@.id=='A')] or $..ids[?(@.id=='A')]

with result:

[
   {
      "id" : "A"
   }
]

but I would like to access the value of its sibling ("value": "one").

Thanks in advance!


Solution

  • You can also use the in filter operator.

    $.elements[?('A' in @.ids.*.id)].value