jsontypescriptjsonpathjson-path-expressionjsonpath-plus

JSONPath getting Error when square brackets inside of string


kI have a problem with the library https://github.com/JSONPath-Plus/JSONPath at the latest version.

Example:

{
    "firstName": "John",
    "lastName": "doe",
    "age": 26,
    "address": {
        "streetAddress": "naist street",
        "city": "Nara",
        "postalCode": "630-0192"
    },
    "phoneNumbers [1]": [
        {
            "type": "iPhone",
            "number": "0123-4567-8888"
        },
        {
            "type": "home",
            "number": "0123-4567-8910"
        }
    ]
}

Now i want to get "phoneNumbers [1]" with

path: $..['phoneNumbers [1]']

Here is a Demo Page for testing: https://jsonpath-plus.github.io/JSONPath/demo/

That did not work because of the square brackets inside of the String. Do anyone know how to solve this Problem.

I have a lot of Json Objects containing strings with square brackets, so if there is a solution not only for a specific case.

Is there any option to escape characters so that the problem will be solved? The json Object above is only a Example Code to describe the Problem.

The Problem also occurs when only using JSONPath so it is not limited to that Library.

https://jsonpath.com/


Solution

  • This appears to be a bug in JSONPath-Plus. The jsonpath library can handle it.

    const data = JSON.parse(`{
        "firstName": "John",
        "lastName": "doe",
        "age": 26,
        "address": {
            "streetAddress": "naist street",
            "city": "Nara",
            "postalCode": "630-0192"
        },
        "phoneNumbers [1]": [
            {
                "type": "iPhone",
                "number": "0123-4567-8888"
            },
            {
                "type": "home",
                "number": "0123-4567-8910"
            }
        ]
    }`);
    const result = jsonpath.query(data, "$..['phoneNumbers [1]']");
    console.log(result);
    <script src="https://unpkg.com/jsonpath@1.1.1/jsonpath.js"></script>

    There's not much you can do about this beyond: