Brijesh Gandhi
Brijesh Gandhi

Reputation: 570

How can I get parent node in JSONPATH

I have sample json format as per below

var myJSON = {
    section: "main",
    title: "xyz",
    child: [{
        title: "Home",
        isEnable: false,
        isActive: true
    }, {
        title: "Contact",
        isEnable: false,
        isActive: true
    }, {
        title: "Menu",
        isEnable: true,
        child: [{
            title: 'Sub-Menu-1',
            isEnable: true
        }, {
            title: 'Sub-Menu-2',
            isEnable: true,
            child: [{
                title: 'Sub-Menu-2-1',
                isEnable: false,
                isActive: true
            }, {
                title: 'Sub-Menu-2-2',
                isEnable: false,
                isActive: true
            }]
        }, {
            title: 'Sub-Menu-3',
            isEnable: true
        }, {
            title: 'Sub-Menu-4',
            isEnable: true
        }]
    }]
};

I want to get whole object with title name Sub-Menu-2 if I match title with one of its child sub-menu title. I have tried as per below but I didn't get as per my expectation

var result = jsonPath(myJSON , '$..*[?(@.title == "Sub-Menu-2-1")]');

my expected output is below

{
    title: 'Sub-Menu-2',
    isEnable: true
    child: [{
        title: 'Sub-Menu-2-1'
        isEnable: false,
        isActive: true
    }, {
        title: 'Sub-Menu-2-2',
        isEnable: false,
        isActive: true
    }]
}

Please help me to get expected output .Thanks in advance

Upvotes: 3

Views: 5173

Answers (2)

Jerry Jeremiah
Jerry Jeremiah

Reputation: 9643

You need to find a node containing a child attribute that contains a title 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:

$..[?(@.child[?(@.title=='Sub-Menu-2-1')] empty false)].title

Upvotes: 0

Pramod Karandikar
Pramod Karandikar

Reputation: 5329

For your expected output, you need to change the JSONPath expression.

$..[?(@.title =="Sub-Menu-2")]

This will give you the output:

[
    {
        "title": "Sub-Menu-2",
        "isEnable": true,
        "child": [
            {
                "title": "Sub-Menu-2-1",
                "isEnable": false,
                "isActive": true
            },
            {
                "title": "Sub-Menu-2-2",
                "isEnable": false,
                "isActive": true
            }
        ]
    }
]

Upvotes: 1

Related Questions