0

I have a json object with numeric keys in an example.json file:

{
  "1": "foo",
  "2": "bar"
}

I want to get its properties by key via jq, and I have tried:

$ jq ."1" example.json
0.1

and

jq .["1"] example.json
jq: error (at example.json:4): Cannot index object with number

The result should be

"foo"

though.

peak
  • 105,803
  • 17
  • 152
  • 177
k0pernikus
  • 60,309
  • 67
  • 216
  • 347
  • https://stackoverflow.com/questions/52460453/how-to-use-jq-for-a-query-where-key-is-a-numeric-string – igbins09 Jul 26 '22 at 00:14
  • The following link answers your question https://stackoverflow.com/questions/52460453/how-to-use-jq-for-a-query-where-key-is-a-numeric-string – igbins09 Jul 26 '22 at 00:15

2 Answers2

2

The command:

jq ."1" example.json

doesn't work because the quotes are interpreted by the shell and the first argument that jq receives is .1. The command above is identical to jq .1 example.json and it is not correct as jq reports.

You need to enclose the jq program in apostrophes to prevent the shell interpret any character in it:

jq '."1"' example.json

This way, jq receives ."1" as its program and happily interprets it.

You can also put the key name into square brackets (as you have already tried) but it doesn't add any improvement, it's the same program only bloated. And it gives you more reasons to put it into apostrophes to protect it from the shell:

jq '.["1"]' example.json
axiac
  • 68,258
  • 9
  • 99
  • 134
1

Use quotes:

$ jq '."1"' example.json
"foo"
k0pernikus
  • 60,309
  • 67
  • 216
  • 347