2

I am working with the Jayway JsonPath library to obtain the correct 'id' from below JSON where my phoneNumbers type is 'iPhone'.

In general, I would like to know how to find something from the root element of a block when a specific condition is specified in the sub-JSON objects.

I tried below expressions that select the block associated with iPhone type and also a list of ids respectively, but I am not able to get to the root element id belonging to the JSON object where my phone type is iPhone. Can someone please guide me? I need to get the id as 1 for this question.

To get the list of ids: $[*].id

To get the json object corresponding to iPhone type: $[*].phoneNumbers[?(@.type=='iPhone')]

[
    {
        "id": "1",
        "phoneNumbers": [
            {
                "type": "iPhone",
                "number": "0123-4567-8888"
            },
            {
                "type": "home",
                "number": "0123-4567-8910"
            }
        ]
    },
    {
        "id": "2",
        "phoneNumbers": [
            {
                "type": "x",
                "number": "0123-4567-8888"
            },
            {
                "type": "y",
                "number": "0123-4567-8910"
            }
        ]
    }
]
wp78de
  • 18,207
  • 7
  • 43
  • 71
Dwarrior
  • 687
  • 2
  • 10
  • 26
  • This works for me using Jayway's JsonPath [here](https://jsonpath.herokuapp.com/). What do you think? – wp78de Nov 12 '20 at 02:10

1 Answers1

0

I think you want your expression to look deeper.

First, find the objects that have an iPhone in the phone numbers list. Then just select the IDs.

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


Edit

It looks like the Java JsonPath library (I think you're using this) supports a number of functions. It doesn't list a contains(), but you might try the anyof operator:

$[?(@.phoneNumbers[*].type anyof ["iPhone"])].id

Note that this is definitely implementation-specific and will likely not work with any other library.

gregsdennis
  • 7,218
  • 3
  • 38
  • 71
  • I tried your suggestion here - https://jsonpath.com/ but it didn't give me any result. Kindly let me know if you tested this expression elsewhere and it worked so that I can validate. – Dwarrior Oct 06 '20 at 17:28
  • Yeah, there are some nuances in that expression that probably aren't widely supported. I'll try to think of another way to do it. – gregsdennis Oct 08 '20 at 04:57