109

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.

4
  • 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 <something>" 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
    Commented Dec 9, 2021 at 12:33
  • I tried to edit it myself but just got: "Suggested edit queue is full", whatever that means.
    – Onkeltem
    Commented Dec 9, 2021 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
    Commented May 18, 2022 at 2: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. Commented Jul 24, 2023 at 9:54

1 Answer 1

184

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
1
  • Good answer, thanks for the -r tip too for removing the quotes, super handy.
    – kramfs
    Commented Sep 26, 2020 at 5:49

Not the answer you're looking for? Browse other questions tagged or ask your own question.