python-3.x - 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)
解决方案
我找到了逃避它的正确方法:
jmespath.search("\"@name\"", json)
根据我使用 JMESPath 的经验,对象的某些属性需要双引号,例如,如果我有一个 object {"0": "txt", "name": "txt2"}
,我可以使用此命令访问 name 值,@.name
但对于0
值,我需要在零周围加上双引号。我不能这样做@.0
(它不起作用),但添加双引号是有效@."0"
的。这可能就是 JMESPath 不允许双引号定义字符串的原因。因此,这与将某些特殊字符放入属性中的情况相同。在 Python 中,查询已经是一个字符串,所以需要添加额外的引号并转义内引号\"
来解决这个问题。
在 JavaScript 中,您可以使用'"@name"'
.
推荐阅读
- flutter - Flutter - 文本小部件更新一次迭代太晚了
- flutter - 显示从 TimePicker 中选择的时间以在 Flutter App 中显示本地通知
- android - 尝试写入文件时如何解决 Flutter 错误:“OS 错误:不允许操作,errno = 1”?
- proc-sql - SQL:有没有办法在同一个 SELECT 语句中使用新的/用户定义的变量?
- android - 想知道继续以下 Rx 链的最佳方式是什么,我需要决定调用 flatmap 还是 switchmap?
- html - 为什么文本会超出 div 容器?
- visual-studio-code - 调试控制台出错时跳转到链接的快捷方式是什么?
- python - 将值插入目录路径的字符串中不起作用
- azure - 为什么我的应用无法与 azure 应用服务上的 websocket 通信?
- sql-server - 在 DBeaver (MAC) 上为 SQL Server 连接本地主机