how to escape special character colon (':') in jsonpath

Viewed 3872

Json:

{
    "im:rating": {
        "label": "1"
    }
}

While trying to use Jsonpath in groovy If i am using this '$.im:rating'

It is showing following error

Caused by: com.nebhale.jsonpath.InvalidJsonPathExpressionException: Illegal

character 'PathCharacter [types=[], value=:, position=4]' $.im:rating ----^ Illegal character 'PathCharacter [types=[SIMPLE_NAME_CHARACTER, LETTER, COMPLEX_NAME_CHARACTER], value=r, position=5]' $.im:rating -----^ Illegal character 'PathCharacter [types=[SIMPLE_NAME_CHARACTER, LETTER, COMPLEX_NAME_CHARACTER], value=a, position=6]' $.im:rating ------^ Illegal character 'PathCharacter [types=[SIMPLE_NAME_CHARACTER, LETTER, COMPLEX_NAME_CHARACTER], value=t, position=7]' $.im:rating -------^ Illegal character 'PathCharacter [types=[SIMPLE_NAME_CHARACTER, LETTER, COMPLEX_NAME_CHARACTER], value=i, position=8]' $.im:rating --------^ Illegal character 'PathCharacter [types=[SIMPLE_NAME_CHARACTER, LETTER, COMPLEX_NAME_CHARACTER], value=n, position=9]' $.im:rating ---------^ Illegal character 'PathCharacter [types=[SIMPLE_NAME_CHARACTER, LETTER, COMPLEX_NAME_CHARACTER], value=g, position=10]' $.im:rating ----------^

  at com.nebhale.jsonpath.JsonPath.compile(JsonPath.java:85)
  at com.nebhale.jsonpath.JsonPath.read(JsonPath.java:182)
3 Answers

I'm assuming you are using the JsonPath library at:

https://github.com/nebhale/JsonPath

In general it is bad form on stack overflow to not post a proper code example and not refer to the exact library (including version) you are using. Without this information the community is left guessing and doing research on your part.

With that said, my take would be that this is a limitation of that specific JsonPath library and as far as I understand it, it is in this specific case not adhering to the json specification.

The following code:

@Grab('com.nebhale.jsonpath:jsonpath:1.2')
import com.nebhale.jsonpath.*

def path = JsonPath.compile('$.im:rating')

when run, results in the error you are describing.

If we instead try using the built-in groovy JsonSlurper:

import groovy.json.*

def json = '''\
{
    "im:rating": {
        "label": "1"
    }
}'''

def parsed = new JsonSlurper().parseText(json)
println "value: ${parsed['im:rating']}"

we get:

~> groovy use_slurper_instead.groovy
value: [label:1]

i.e. there are no problems using keys with : characters in them. I would raise an issue with JsonPath.

We can access alternatively with the following

'$..label'

Related