2015-12-31 4 views
13

Ho quanto segue in un file (che chiamerò "myfile"):JQ: non può indicizzare array con stringhe

[{ 
    "id": 123, 
    "name": "John", 
    "aux": [{ 
     "abc": "random", 
     "def": "I want this" 
    }], 
    "blah": 23.11 
}] 

posso analizzarlo senza il [ e ] come segue:

$ cat myfile | jq -r '.aux[] | .def' 
I want this 
$ 

ma con la [ e ] ottengo:

$ cat myfile | jq -r '.aux[] | .def' 
jq: error: Cannot index array with string 

Come posso gestire lo [ e il ] utilizzando jq? . (Sono sicuro che avrei potuto analizzare loro fuori con uno strumento diverso, ma io voglio imparare l'uso corretto di JQ

risposta

26

Dovrebbe essere:

jq '.[].aux[].def' file.json 

.[] itera oltre la matrice esterna, .aux[] poi itera la aux la matrice di ogni nodo e .def stampe loro .def proprietà

Questo stamperà:.

"I want this" 

Se si vuole sbarazzarsi delle virgolette passare -r (--raw) per jq:

jq -r '.[].aux[].def' file.json 

uscita:

I want this 
+0

Ah, vedo che sta già utilizzando '-r' nella questione . Comunque, non fa male! :) – hek2mgl