jq: Cannot index array with string

JsonJq

Json Problem Overview


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.

Json Solutions


Solution 1 - Json

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionXu WangView Question on Stackoverflow
Solution 1 - Jsonhek2mglView Answer on Stackoverflow