Search code examples
python-3.xjmespath

How do I escape the '@' symbol inside a string literal key for a jmespath search query


I am using jmespath to search a snippet of JSON, and one of the JSON keys contains an '@' symbol. Since the '@' symbol is a reserved character, jmespath chokes. I have tried a number of things to escape the '@' symbol unsuccessfully. How do I escape the '@' symbol in my jmespath search?

Example:

json = {"@name": "Bob", "address": "123 Main St"}

jmespath.search("@name", json)

Error message:

{ParseError} Unexpected token: name: Parse error at column 1, token "name" (UNQUOTED_IDENTIFIER), for expression: "@name" ^

I have also tried the following variations for the above jmespath query, with the same error:

jmespath.search("!@name", json)
jmespath.search("\@name", json)
jmespath.search("`@`name", json)
jmespath.search("\"@\"name", json)

Solution

  • I found the correct way to escape it:

    jmespath.search("\"@name\"", json)
    

    In my experience with JMESPath, some attributes from an object need to be double-quoted, for example, if I have an object {"0": "txt", "name": "txt2"}, I can access the name value with this command @.name but for a 0 value I need to put double quotes around the zero. I can't do this @.0 (it doesn't work), but adding double quotes works @."0". This is probably why JMESPath doesn't allow double quotes to define a string. So this is the same case where you put certain special characters in an attribute. In Python, the query is already a string, so you need to add additional quotes and escape the inner quotes \" to solve this problem.

    In JavaScript, you can achieve the same result with '"@name"'.