Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 834
Abhijeet Rastogi Avatar asked Jul 24 '18 08:07

Abhijeet Rastogi


2 Answers

You just need to quote the key:

$ echo '...' | jq '.abc."@def-ghi"'
"value1"
like image 68
chepner Avatar answered Oct 13 '22 13:10

chepner


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.)

like image 22
peak Avatar answered Oct 13 '22 12:10

peak