Home > Enterprise >  JSONPath : How to filter nested array?
JSONPath : How to filter nested array?

Time:06-23

I have a json like below:

[
    {
        "skuId": "1234",
        "plans": [
            {
                "plan": {
                    "planName": "plan1",
                    "planId": "abcd1231",
                }
            },
            {
                "plan": {
                    "planName": "plan2",
                    "planId": "loks3123",
                }
            }
        ]
    },
    {
        "skuId": "5341",
        "plans": [
            {
                "plan": {
                    "planName": "plan3",
                    "planId": "awer3234",
                }
            },
            {
                "plan": {
                    "planName": "plan4",
                    "planId": "gefd4231",
                }
            }
        ]
    },
    {
        "skuId": "7649",
        "plans": [
            {
                "plan": {
                    "planName": "plan5",
                    "planId": "kitv5397",
                }
            }
        ]
    }
]

Now i have a planId "loks3123", and i want to get the skuId where it belongs to. In this case planId "loks3123" belongs to skuId "1234". Is it possible using JsonPath to do that? If so, How to do that using JsonPath? If not, what should i do? Thanks!

CodePudding user response:

You need to find a node containing a plans attribute that contains a planId attribute that matches your text. Using the suggestion at the end of https://github.com/json-path/JsonPath/issues/287 you can get what you want with:

$..[?(@.plans[?(@.plan.planId == 'abcd1231')] empty false)].skuId

CodePudding user response:

Here is a simple implementation for your problem using javascript and in the solution 'data' is your json data

    let findstring="loks3123";
    for(var i=0;i<data.length;i  ){
        let sku=data[i];
        for(var j=0;j<sku.plans.length;j  ){
            let plans=sku.plans[j];
            if(plans.plan.planId==findstring){
                console.log("skuId:" sku.skuId);
            }
        }
    }

CodePudding user response:

If you are using Jayway JsonPath you can use filter operator in

$..[?('loks3123' in @.plans[*].plan.planId)].skuId

Try here : https://jsonpath.herokuapp.com/

  • Related