Search code examples
jsonjsonpathjson-path-expression

How to write JSON Path to get particular value based on string filter?


I am new to JSON Path and I am trying to get 'id' corresponding to name='Candy' using JsonPath in below JSON payload.

{
    "responsePayload": [
        {
            "content": {             
                "id": "101",               
                "name": "Candy"                
            },
            "links": [
                {
                    "rel": "self",
                    "link": "api/v1/sweets/101",
                    "id": "101"
                }
            ]
        },
        {
            "content": {                
                "id": "102",               
                "name": "Chocolate"
            },
            "links": [
                {
                    "rel": "self",
                    "link": "api/v1/sweets/102",
                    "id": "102"
                }
            ]
        }
    ]
}

For this I tried Jsonpath $.responsePayload[0].content[?(@.name=='Candy')].id but that is not working. I am using https://jsonpath.com/ for testing this JsonPath. Please guide me how I can achieve required result.


Solution

  • You're really close. You need more of the path inside the expression.

    $.responsePayload[?(@.content.name=='Candy')].content.id
    

    The [0] you have in your response isolates the first element only, but it sounds like you want to iterate over the whole array in responsePayload. To do that, the filter expression selector [?(...)] must act on that array.

    Next, the @ represents the current item, and you can build a full path off of it. You can see how that works above.

    Finally, the filter expression selector returns the full item when the expression returns true. So you then need to navigate into .content.id again to get the value you're after.