如何在JSONPATH中获取父节点

时间:2022-09-10 13:38:02

I have sample json format as per below

我有如下所示的json格式示例

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

如果我用它的子菜单标题匹配标题,我想要获得标题名称子菜单2的整个对象。我已经按下面的方法试过了,但是没有达到我的期望

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

请帮助我取得预期的产量。谢谢。

1 个解决方案

#1


1  

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

对于预期的输出,需要更改JSONPath表达式。

$..[?(@.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
            }
        ]
    }
]

#1


1  

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

对于预期的输出,需要更改JSONPath表达式。

$..[?(@.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
            }
        ]
    }
]