jsonpathjson-path-expression

get JSON object having specific key including root JSON object


Hi I'm struggling to find the JSONPATH expression to get all the JSON object having a specific key including the root JSON object. For example:

{
    "key1": 1,
    "key2": 2,
    "key3": {
        "key1": 4,
        "key4": 5,
        "key5": {
            "key1": true
        }
    }
}

should return

[
    {
        "key1": 1,
        "key2": 2,
        "key3": {
            "key1": 4,
            "key4": 5,
            "key5": {
                "key1": true
            }
        }
    },
    {
        "key1": 4,
        "key4": 5,
        "key5": {
            "key1": true
        }
    },
    {
        "key1": true
    }
]

I tried multiple combination with the closest one being $..*[?(@.key1)] but it failed to return the root JSON object.

Thank you for helping me.


Solution

  • I actually raised this while we were finalizing the spec (RFC 9535).

    https://github.com/ietf-wg-jsonpath/draft-ietf-jsonpath-base/issues/390

    Essentially, recursive descent (the ..) only looks at descendants, not the root.

    There's some further discussion there, and you're welcome to add your 2¢. If anything, it could be as part of a JSON Path v2 (if that happens).