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.
|
|
To achieve this, you can use the bash snippet below:
|
|
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:
|
|
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:
|
|
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:
|
|