How to iterate through JSON arrays in Bash using jq
Learn the simple process of iterating through a JSON array in bash with the help of jq
.
Iterate through a JSON array using jq
Scenario: You have a file named projects.json
contains an array named “projects” that you want to iterate through.
1{
2 "projects": [
3 {
4 "name": "project 1",
5 "owner": "owner 1",
6 "id": 1,
7 "version": "2.3.0"
8 },
9 {
10 "name": "project 2",
11 "owner": "owner 1",
12 "id": 2,
13 "version": "1.54.0"
14 },
15 {
16 "name": "project 3",
17 "owner": "owner 2",
18 "id": 3,
19 "version": "4.9.2"
20 }
21 ]
22}
To achieve this, you can use the bash snippet below:
1jq -c '.projects[]' projects.json | while read i; do
2 echo "$i"
3done
The command uses jq to extract each object in the “projects” array and then uses a while loop to iterate through the extracted objects. The echo statement prints each object.
The output will be:
1{"name":"project 1","owner":"owner 1","id":1,"version":"2.3.0"}
2{"name":"project 2","owner":"owner 1","id":2,"version":"1.54.0"}
3{"name":"project 3","owner":"owner 2","id":3,"version":"4.9.2"}
Iterate through a JSON array using jq
and associative arrays in Bash
If your version of bash supports associative arrays, you can use an alternative approach:
1readarray -t projects < <(jq -c '.projects[]' projects.json)
2for i in "${projects[@]}"; do
3 echo "$i"
4done
This command stores each object from the “projects” array in an associative array called projects. Then, it uses a for loop to iterate through the objects and echo to print each object.
The output will be the same as before:
1{"name":"project 1","owner":"owner 1","id":1,"version":"2.3.0"}
2{"name":"project 2","owner":"owner 1","id":2,"version":"1.54.0"}
3{"name":"project 3","owner":"owner 2","id":3,"version":"4.9.2"}