Escape field name in jq that contains '@' and '-'? [duplicate]

家住魔仙堡 提交于 2019-12-17 06:55:10

问题


Input JSON:

{
  "abc": {
    "@def-ghi": "value1",
    "xyz": "value2"
  }
}

And I'm trying to get value for field @def-ghi.

➜ $?=0 ➤ echo '{"abc": {"@def-ghi": "value1", "xyz": "value2"}}' | jq '.abc.xyz'
"value2"
➜ $?=0 ➤ echo '{"abc": {"@def-ghi": "value1", "xyz": "value2"}}' | jq '.abc.@def-ghi'
jq: error: syntax error, unexpected '-', expecting QQSTRING_START (Unix shell quoting issues?) at <top-level>, line 1:
.abc.@def-ghi
jq: 1 compile error
➜ $?=3 ➤

How to escape the field name properly?


回答1:


You just need to quote the key:

$ echo '...' | jq '.abc."@def-ghi"'
"value1"



回答2:


The most robust alternative is to use the basic form:

.[KEY]

where KEY is a JSON string, including the outer quotation marks.

This form, however, must be pipelined, so you'd have to write:

jq '.abc|.["@def-ghi"]'

(The .[_] form can also be used for arrays, but of course _ would have to be an integer.)



来源:https://stackoverflow.com/questions/51494389/escape-field-name-in-jq-that-contains-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!