jsonjsonpath

Get first array element to meet a condition in JSONPath


Given a JSON object with an array —e.g.:

{
  "phoneNumbers": [
    {
      "type"  : "iPhone",
      "number": "0000-0000-0000"
    },
    {
      "type"  : "home",
      "number": "1111-1111-1111"
    },
    {
      "type"  : "home",
      "number": "2222-2222-2222"
    }
  ]
}

Is there a way to get only the first element in the array that meets a condition? I'm using this expression $.phoneNumbers[?(@.type=="home")].number, but this of course gives me all the elements that meet the condition.

[
  "1111-1111-1111",
  "2222-2222-2222"
]

I wonder if there's a way to get just 1111-1111-1111.


Edit:

After looking at another question that's slightly related I've found this in the docs:

Please note, that the return value of jsonPath is an array, which is also a valid JSON structure.

So... getting a string is not possible, but I'd still like to see if it's possible to get an array of a single element, that being the first one to meet the condition —e.g.:

[
  "1111-1111-1111"
]

Solution

  • There is a thread that talks about this https://github.com/json-path/JsonPath/issues/272.

    Looks like as of 29.05.2025, there is still no way to slice it directly in one step, therefore you would have to do post-processing i.e., filter out the first element after the query results.