Forum Discussion

dhammika's avatar
dhammika
New Contributor
7 years ago

JSON Path evaluation

In the property transfer "$.persons[*].phoneNumbers[0].type" JSON path is evaluated against the following JSON  to extract values.

It gives me value [iPhone]

But I'm expecting value ["iPhone","iPhone","iPhone"], which is the one I'm getting from online json path evaluators.

Can someone explain why the difference and what should I do to get the expected results.

{

"persons": [
{
"firstName": "John",
"lastName": "doe",
"age": 26,
"address": {
"streetAddress": "naist street",
"city": "Nara",
"postalCode": "630-0192"
},
"phoneNumbers": [
{
"type": "iPhone",
"number": "0123-4567-8888"
},
{
"type": "home",
"number": "0123-4567-8910"
}
]
},
{
"firstName": "John",
"lastName": "doe",
"age": 26,
"address": {
"streetAddress": "naist street",
"city": "Nara",
"postalCode": "630-0192"
},
"phoneNumbers": [
{
"type": "iPhone",
"number": "0123-4567-8888"
},
{
"type": "home",
"number": "0123-4567-8910"
}
]
},
{
"firstName": "John",
"lastName": "doe",
"age": 26,
"address": {
"streetAddress": "naist street",
"city": "Nara",
"postalCode": "630-0192"
},
"phoneNumbers": [
{
"type": "iPhone",
"number": "0123-4567-8888"
},
{
"type": "home",
"number": "0123-4567-8910"
}
]
}
]
}

 

 

 

  • Remove the [0] behind phoneNumbers, since it only retrieves the very first occurens.

    Like this: $.persons[*].phoneNumbers.type
    • dhammika's avatar
      dhammika
      New Contributor

      It will not give me the expected result

      It is giving me following result, which is not the first phone types, rather all the phone types.

      [[iPhone, home, iPhone2, home, iPhone3, home]]

      What I require is every person's first phone types which is as I mentioned earlier

       ["iPhone","iPhone","iPhone"]

       

       

       

      • Alex99's avatar
        Alex99
        Contributor

        You are right, try this one:

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

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

         

        *edit: changed expression

        But, just to point out, you asked for the type first, not the number.

        -->> But I'm expecting value ["iPhone","iPhone","iPhone"], which is the one I'm getting from online json path evaluators.