2

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?

1 Answer 1

1

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"]
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Dev. This unfortunately seems to be getting around the problem. If I have multiple items of type iPhone then I think this solution suffers the same problem I originally described.
It does not, see the complete answer. I have given a choice as per the sample data. Now if only first occurrence of number you want you can go for the index as described in the answer. Also what ever you have explain in the question is not what you are saying in the comment. Your JSON expression is incorrect in first place.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.