skip to Main Content
{
  "a": [
    {
      "b": {
        "c": [
          {
            "id": "123"
          }
        ],
        "d": {
          "e": {
            "f": [
              {
                "name": "abc",
                "type": "in"
              },
              {
                "name": "xyz",
                "type": "out"
              }
            ]
          }
        }
      }
    },
    {
      "b": {
        "c": [
          {
            "id": "456"
          }
        ],
        "d": {
          "e": {
            "f": [
              {
                "name": "def",
                "type": "out"
              },
              {
                "name": "pqr",
                "type": "out"
              }
            ]
          }
        }
      }
    }
  ]
}

I am trying to extract the id’s for which type=’in’. So, as per the above example , the output should be 123 as only abc in the first element has the type ‘in’.
I tried multiple ways but not succeeded to extract it. Can someone please help on this?

With the following expression I am able to extract the node whose value is ‘in’ but how to extract the corresponding id/id’s of the same object (i.e. 123)?

$.a[*].b.d[*].f[?(@.type=='in')]

Can try the json path here :
JSON path online tool

2

Answers


  1. $.a is gives you an array and you want to access first item of array and the c object is also has an array value.
    So the way is like;

    $.a[0].b.c[0].id will give you the result 123

    Login or Signup to reply.
  2. You want

    $.a[[email protected][[email protected] == 'in']].b.c.*.id
    

    NOTE: .* and [*] are equivalent.

    This will search for all elements in $.a which contain a @.b.d.e.f which contains @.type == 'in', then it queries the result of that to get .b.c.*.id

    The key is using nested queries.

    • The outer query @.b.d.e.f[[email protected] == 'in'] acts on the elements of a and is an existence test: it doesn’t have any comparisons. If the test returns a non-empty result, then the element is selected.
    • The inner query @.type == 'in' acts on the elements of f and checks for the condition that you want.

    The final piece is simply navigating to the information you want (.b.c.*.id) from the elements of a that are returned.


    This is compliant with the pending IETF JSON Path specification, which can be tested in my playground https://json-everything.net/json-path.

    Not all libraries will be compliant with the specification. You’ll need to check with the library you’re using to see what’s supported.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search