Jq: Parsing keys with - character doesn't work

Created on 7 Sep 2015  路  5Comments  路  Source: stedolan/jq

It's not posible to parse { "app-code": "123456" } string due to - character.

PoC code under Linux:

$ jq --version
jq-1.5
$ cat data.json
{
  "app-code": "1234567890"
}
$ cat data.json  | jq .app-code
jq: error: code/0 is not defined at <top-level>, line 1:
.app-code     
jq: 1 compile error
$ cat data.json  | jq ".app-code"
jq: error: code/0 is not defined at <top-level>, line 1:
.app-code     
jq: 1 compile error
$ cat data.json  | jq '.app-code'
jq: error: code/0 is not defined at <top-level>, line 1:
.app-code     
jq: 1 compile error
$ cat data.json  | jq '.app\-code'
jq: error: syntax error, unexpected INVALID_CHARACTER, expecting $end (Unix shell quoting issues?) at <top-level>, line 1:
.app\-code    
jq: 1 compile error
$ cat data.json  | jq ".app\-code"
jq: error: syntax error, unexpected INVALID_CHARACTER, expecting $end (Unix shell quoting issues?) at <top-level>, line 1:
.app\-code    
jq: 1 compile error
support

Most helpful comment

You can use ."" syntax, like jq '."app-code"'

All 5 comments

You can use ."" syntax, like jq '."app-code"'

Or jq '.["app-code"]' if you find that more readable.

That worked, thank you.

Please, consider adding this in some place in the documentation. Maybe it's already in place and I missed, but it's definitively helpful.

Thanks again.

anyone have a suggestion for handling a situation where the filter is a variable? ex:

$ str="app-code"
$ cat data.json | jq ".${str}"

Here is a solution using the generally recommended approach:

jq --arg k "$str" '.[$k]'

For future reference, please post usage questions at https://stackoverflow.com/questions/tagged/jq

Was this page helpful?
0 / 5 - 0 ratings

Related issues

tischwa picture tischwa  路  4Comments

lhunath picture lhunath  路  3Comments

thedward picture thedward  路  3Comments

mcandre picture mcandre  路  3Comments

thelonious picture thelonious  路  4Comments