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

一个人想着一个人 提交于 2019-12-11 06:08:18

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/52460453/how-to-use-jq-for-a-query-where-key-is-a-numeric-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!