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?
You just need to quote the key:
$ echo '...' | jq '.abc."@def-ghi"'
"value1"
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With