Search code examples
keyspecial-charactersjq

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


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?


Solution

  • You need to quote the key:

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