JSONPath getting Error when square brackets inside of string

1.2k views Asked by At

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/

2

There are 2 answers

0
Quentin On BEST ANSWER

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/[email protected]/jsonpath.js"></script>

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

  • Changing your data structure
  • Changing your library
  • Filing a bug report
0
Akshay G On

There is a workaround you can use only with jsonpath-plus

$[?(@property == "phoneNumbers [1]")]