How to use jq for a query where key is a numeric string
Asked Answered
Y

1

3

Recently discovered jq and am using it to format some data.

How do I use it to access fields of a json object that happen to be numeric strings?

For example, the following fails for me with an error:

echo '{"20":"twenty"}' | jq .["20"]

What's the right way to do this?

Yiyid answered 22/9, 2018 at 20:6 Comment(1)
Purely a shell problem, not a jq problem. The shell isn't passing the quotes to jq at all, because it's parsing them as syntaxBrooking
B
4

Immediate Answer: Use More Quotes

In jq .["20"], the double quotes are parsed as shell syntax, not jq syntax (shell quoting is character-by-character: One can switch quoting types within a larger string). Use single quotes to protect that entire string from modification by the shell:

$ echo '{"20":"twenty"}' | jq '.["20"]'
"twenty"

Finding The Problem Yourself

One approach to diagnosing this kind of problem is using the shell's xtrace facility, to tell the shell to echo back to you the command lines it's running:

$ set -x
$ echo '{"20":"twenty"}' | jq .["20"]
+ echo '{"20":"twenty"}'
+ jq '.[20]'
jq: error (at <stdin>:1): Cannot index object with number

As you can see, jq .["20"] was parsed as being identical to jq '.[20]'

Brooking answered 22/9, 2018 at 21:5 Comment(1)
Other variations in a bash-like environment: jq '."20"', jq '.[20|tostring]', and jq 'getpath(["20"])'Tops

© 2022 - 2024 — McMap. All rights reserved.