syntaxjqinvocation

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


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?


Solution

  • 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]'