home / guides

Itterate through a JSON file in Bash

Assume that you have a file of people, this file called “people.json”, which looks something like this . . .


Now, you may want to itterate on each of those json objects to get the values of each.

This is easy to do with the “jq” command like the following:

read_json() {
	while IFS= read -r NAME && IFS= read -r FAVCOLOR; do
		echo "${NAME}'s favorite color is ${FAVCOLOR}"
	done < <(jq -r ".[] | .name, .favorite_color" ./people.json)

The output of the above command should look like this:

Bob's favorite color is red
Doug's favorite color is blue
Samantha's favorite color is red
Jessica's favorite color is green

Detailed Explaination

Using the raw output from JQ, we can then itterate over every json as if it was an entry from an array. Then using the named pipes, we can name the Inputs for the READ command.

--raw-output / -r: - With this option, if the filter's result is a string then it will be written directly to standard output rather than being formatted as a JSON string with quotes. This can be useful for making jq filters talk to non-JSON-based systems. -- jq man pages

While we are looping, the the -r option on read prevents it from treating backslash as a special character. -- man for bash / read

⬅️ Back to Guides