|
> gives me the feeling of looking into cryptic Perl or regex Dunno if you'll see this given how many replies you already got, but rather than just dumping "how do you do that" here's a realization I had a while ago that made it way easier to understand: jq's language is a series of filters/transformers more akin to bash pipes on a stream of data than anything else. For example, just "." selects out the current object (and is needed to match the "root" at the start of the query), and jq pretty-prints the results (when to a terminal): $ echo '[{"k1": "v1", "k2": "v2"}, {"k1": "v3"}]'
[{"k1": "v1", "k2": "v2"}, {"k1": "v3"}]
$ echo '[{"k1": "v1", "k2": "v2"}, {"k1": "v3"}]' | jq '.'
[
{
"k1": "v1",
"k2": "v2"
},
{
"k1": "v3"
}
]
There's only 1 matching element here, the outermost array. We want to go one deeper, so use "[]" to unwrap/flatten it: $ echo '[{"k1": "v1", "k2": "v2"}, {"k1": "v3"}]' | jq '.[]'
{
"k1": "v1",
"k2": "v2"
}
{
"k1": "v3"
}
jq is now iterating over 2 objects, so the next filter is the one where you select out the key you want. This can be done in two different ways for this example (per sibling replies): $ echo '[{"k1": "v1", "k2": "v2"}, {"k1": "v3"}]' | jq '.[].k1'
"v1"
"v3"
$ echo '[{"k1": "v1", "k2": "v2"}, {"k1": "v3"}]' | jq '.[] | .k1'
"v1"
"v3"
Note how I broke these up: The atoms are ".", "[]", and ".k1" - ".[]" isn't one of them, despite what it may look like at first glance when compared to ".k1". Some additional examples to show how these combine:The "unwrap/flatten" [] can be used multiple times when nested arrays are involved, with or without the pipe syntax, but only works on arrays. It errors if given something else: $ echo '[[1,2,3],[4,[5,6]]]' | jq '.[]'
[
1,
2,
3
]
[
4,
[
5,
6
]
]
$ echo '[[1,2,3],[4,[5,6]]]' | jq '.[][]'
1
2
3
4
[
5,
6
]
$ echo '[[1,2,3],[4,[5,6]]]' | jq '.[][][]'
jq: error (at <stdin>:1): Cannot iterate over number (1)
$ echo '[[1,2,3],[4,[5,6]]]' | jq '.[] | .[]'
1
2
3
4
[
5,
6
]
$ echo '[[1,2,3],[4,[5,6]]]' | jq '.[] | .[] | .[]'
jq: error (at <stdin>:1): Cannot iterate over number (1)
Also notice how the "." is needed after the pipes; these are separate filters/transformations being chained together, so as a new rule it needs the same "." as with the first one. |