1

Given this json file wtf.json:

{
  "I-am-test-v2": {
    "exist": true
  },
  "works": {
    "exist": true
  }
}

I can verify it has these keys via:

$ jq 'keys' wtf.json 
[
  "I-am-test-v2",
  "works"
]

I can access works via:

$ jq .works wtf.json
{
  "exist": true
}

yet I cannot select:

$ jq .I-am-test-v2 wtf.json

as that will yield in error:

jq: error: am/0 is not defined at <top-level>, line 1:
.I-am-test-v2   
jq: error: test/0 is not defined at <top-level>, line 1:
.I-am-test-v2      
jq: error: v2/0 is not defined at <top-level>, line 1:
.I-am-test-v2           
jq: 3 compile errors

I assume it has to do with the special char -, yet I am unsure how to quote or escape it, as these attempts also fail with the same error:

 jq ".I-am-test-v2"  wtf.json 
 jq ."I-am-test-v2"  wtf.json

or some different error via:

jq ."I\-am\-test\-v2"  wtf.json 
jq: error: syntax error, unexpected INVALID_CHARACTER, expecting $end (Unix shell quoting issues?) at <top-level>, line 1:
.I\-am\-test\-v2  
jq: 1 compile error

I also tried:

jq .["I-am-test-v2"] wtf.json

How am I supposed to access the key?

k0pernikus
  • 60,309
  • 67
  • 216
  • 347
  • 1
    Always quote your filters, preferably in single quotes when available. Otherwise the shell will interpret everything incorrectly and cause problems. – Jeff Mercado Oct 08 '19 at 20:23

2 Answers2

5

Your key contains the dash - that is interpreted as the substraction operator.

You need to tell jq that it's a string by double quoting your key.

If you do that in command line, enclose your jq "script" into single quote in order to avoid your shell interpreting any special characters.

<wtf.json jq '."I-am-test-v2"' 
oliv
  • 12,690
  • 25
  • 45
1

You can access it via proper enquotation via:

jq '.["I-am-test-v2"]' wtf.json 
{
  "exist": true
}

Then it also works with escaping:

jq ".[\"I-am-test-v2\"]" wtf.json 

Note that you cannot reverse the quote style:

jq ".['I-am-test-v2']" wtf.json 
jq: error: syntax error, unexpected INVALID_CHARACTER (Unix shell quoting issues?) at <top-level>, line 1:
.['I-am-test-v2']  
jq: 1 compile error
k0pernikus
  • 60,309
  • 67
  • 216
  • 347