104

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 could parse it if the file did not have the first [ and last ] 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.

Xu Wang
  • 10,199
  • 6
  • 44
  • 78
  • 1
    I reread the question several times to get the idea and then realized that it's asked in a very bad way. There is basically a logical error in the story itself. Xu Wang says: "I can parse it without " and then immediately uses that something! What the heck? So what's the difference between the first and the second case? Could you please fix the question? Please also verify code highlighting. For some reason both pieces are highlighted differently so it's hard to see that the code is the same. – Onkeltem Dec 09 '21 at 12:33
  • I tried to edit it myself but just got: "Suggested edit queue is full", whatever that means. – Onkeltem Dec 09 '21 at 12:42
  • @Onkeltem indeed it was confusing. I am sorry. I made an edit to specify that the `[` and `]` refer to the first `[` in the file and the last `]` in the file. – Xu Wang May 18 '22 at 02:22
  • The question talks of "parsing" it differently, as if the brackets were not there, but jq is all about following JSON standard, requiring these to be parsed as arrays. The answer instead is about looking up values differently, adjusted for the arrays presence. – Beni Cherniavsky-Paskin Jul 24 '23 at 09:54

1 Answers1

177

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
hek2mgl
  • 152,036
  • 28
  • 249
  • 266