Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.7k views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...