Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k views
in Technique[技术] by (71.8m points)

json - jq: Cannot index array with string

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.6k users

...