Search code examples
jsonjsonpath

JsonPath - selecting a node by filtering on the presence of another node


I'm new to JSON path and can't seem to figure uit how to solve my problem. I would like to have an output of all urls corresponding to 'component1'. For validation I used: http://jsonpath.com

This is my JSON file:

{
    "Portfolio":{
        "Website 1":{
            "url":"https://www.website1.com",
            "components":[
                "component1",
                "component2",
                "component3"
            ]
        },
        "Website 2":{
            "url":"https://www.website2.com",
            "components":[
                "component5",
                "component1",
                "component4"
            ]
        }
    }
}

Solution

  • You can do it with:

    $.Portfolio[?(@.components.indexOf('component1') !== -1)].url
    

    Mentioned here, ?() allows you to run JavaScript code as a filter.

    I encourage you to learn exactly what this is doing and make an attempt at the problem yourself next time you post on here.