首页 > 解决方案 > 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)

标签: python-3.xjmespath

解决方案


我找到了逃避它的正确方法:

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

根据我使用 JMESPath 的经验,对象的某些属性需要双引号,例如,如果我有一个 object {"0": "txt", "name": "txt2"},我可以使用此命令访问 name 值,@.name但对于0值,我需要在零周围加上双引号。我不能这样做@.0(它不起作用),但添加双引号是有效@."0"的。这可能就是 JMESPath 不允许双引号定义字符串的原因。因此,这与将某些特殊字符放入属性中的情况相同。在 Python 中,查询已经是一个字符串,所以需要添加额外的引号并转义内引号\"来解决这个问题。

在 JavaScript 中,您可以使用'"@name"'.


推荐阅读