- 1 year ago
jq: Iterate over inner multiple array
Comment
1 / 1
To iterate over multiple inner arrays using jq
, you can use a combination of map
and flatten
functions. Here's an example:
bash# JSON input data
json_data='[
{
"name": "John",
"pets": [
{"type": "dog", "name": "Buddy"},
{"type": "cat", "name": "Whiskers"}
]
},
{
"name": "Alice",
"pets": [
{"type": "bird", "name": "Polly"},
{"type": "fish", "name": "Nemo"}
]
}
]'
# Use jq to iterate over the inner arrays
jq '.[] | .pets | map(.name)' <<< "$json_data"
In this example, we have an array of objects where each object has a "name"
and "pets"
property. We want to iterate over the inner "pets"
arrays and extract the "name"
values.
The jq '.[] | .pets | map(.name)'
expression does the following:
.[]
selects each object in the top-level array.pets
selects the"pets"
property of each objectmap(.name)
iterates over the"pets"
array and extracts the"name"
value for each element
The output will be an array of all the "name"
values from the inner arrays:
css[ "Buddy", "Whiskers", "Polly", "Nemo"]
You can modify the map
expression to extract different properties or perform other transformations as needed.