Search code examples
arraysjsonfilteringjsonpath

JSON Path for element sometimes in an array


I need a JSON path to an "element" when the "condition" is 1

{
  "customer": [
    {
      "Addresses": {
        "addressDetails": {
          "element": "one"
        },
        "Condition": {
          "type": 1
        }
      }
    },
    {
      "Addresses": [
        {
          "addressDetails": {
            "element": "two"
          },
          "Condition": {
            "type": 0
          }
        },
        {
          "addressDetails": {
            "element": "three"
          },
          "Condition": {
            "type": 1
          }
        }
      ]
    }
  ]
}
                                      

As you can see in the example: "Addresses" can sometimes be an array containing multiple details. I need to get the "element" of only those where the "Condition" is equal to 1 - so from this snippet the JSON path should return "one" and "three". Is that possible?

I tried many different ways with filtering using [?(@.==)] but it never worked - I only managed to get the element from either the non-array object or the array object, never both.


Solution

  • What you're looking for is the recursive descent operator ... This will recursively search down the tree. Start with that, and then you can use your filter [?...].

    $..[?(@.Condition.type == 1)]
    

    You can test this on my site: https://json-everything.net/json-path.


    As a side note, with the new RFC 9535, you don't need the paretheses:

    $..[[email protected] == 1]
    

    Note that since is a new spec, implementations are still catching up, so check with the library you're using.