kgf3JfUtW
kgf3JfUtW

Reputation: 14926

JsonPath: getting first element in string list

On https://jsonpath.com I have below example, using expression

$.phoneNumbers[?(@.id < 3)].number

on below JSON object.

{
  "firstName": "John",
  "lastName" : "doe",
  "age"      : 26,
  "phoneNumbers": [
    {
      "type"  : "iPhone",
      "number": "0123-4567-1111",
      "id": 1
    },
    {
      "type"  : "home",
      "number": "0123-4567-2222",
      "id": 2
    },
    {
      "type"  : "home",
      "number": "0123-4567-3333",
      "id": 3
    }
  ]
}

Result is

[
  "0123-4567-1111",
  "0123-4567-2222"
]

Question

I only want the first string "0123-4567-1111", but appending [0] to my expression does not work. Expression $.phoneNumbers[?(@.id < 3)].number[0] gives result ["0","0"]. How can I get the first returned string?

Upvotes: 2

Views: 4859

Answers (1)

Dev
Dev

Reputation: 2813

Indeed you were very close to it by using this expression -

$.phoneNumbers[?(@.id < 3)].number[0]

In this expression you used id but in the json there is no id key so it resulted in undefined

try the expression like this using index -

 $.phoneNumbers[0].number

It will return number from the first object of phoneNumbers list as : ["0123-4567-8888"]

If you want to go by conditional basis use the below expression which will return the number of type iphone -

$.phoneNumbers[?(@.type == 'iPhone')].number

Output -

["0123-4567-8888"]

Upvotes: 1

Related Questions