jq: Cannot index array with string

匿名 (未验证) 提交于 2019-12-03 03:04:01

问题:

I have the following in a file (which I will call "myfile"):

[{     "id": 123,     "name": "John",     "aux": [{         "abc": "random",         "def": "I want this"     }],     "blah": 23.11 }] 

I can parse it without the [ and ] as follows:

$ cat myfile | jq -r '.aux[] | .def' I want this $ 

but with the [ and ] I get:

$ cat myfile | jq -r '.aux[] | .def' jq: error: Cannot index array with string 

How can I deal with the [ and ] using jq? (I'm sure I could parse them off with a different tool but I want to learn correct usage of jq.

回答1:

It should be:

jq '.[].aux[].def' file.json 

.[] iterates over the outer array, .aux[] then iterates over the the aux array of every node and .def prints their .def property.

This will output:

"I want this" 

If you want to get rid of the double quotes pass -r (--raw) to jq:

jq -r '.[].aux[].def' file.json 

Output:

I want this 


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