There are many articles on how to use jq to filter JSON at the command line, but in this article we'll discuss how to use that beautifully filtered JSON in your Bash scripts by assigning the data to Bash variables and arrays.
The simplest technique is to assign a single JSON attribute to a Bash variable and then use that variable in your script. In this example we will convert the output of rpm -qia into JSON with jc, filter with jq, and then assign to a Bash variable to print to the terminal.
$ package_name=$(rpm -qia | jc --rpm-qi | jq 'sort_by(.build_epoch)[] | select(.license == "MIT")' | jq -sr '.[-1].name')
$ echo $package_name
jc
A bit more advanced is to assign a JSON array to a list string variable in Bash:
packages=$(rpm -qia | jc --rpm-qi | jq -r '.[] | select(.license == "MIT") | .name')
for package in $packages; do
echo "Package name is ${package}" > "${package}".txt
done
Finally, you can assign entire JSON objects to Bash array elements so you can assign individual attributes to different variables to be used inside a loop:
# pull the rpm package objects into a bash array from jq
packages=()
while read -r value; do
packages+=("$value")
done < <(rpm -qia | jc --rpm-qi | jq -c '.[] | select(.license == "MIT")')
# iterate over the bash array
for package in "${packages[@]}"; do
name=$(jq -r '.name' <<< "${package}")
description=$(jq -r '.description' <<< "${package}")
version=$(jq -r '.version' <<< "${package}")
echo "Package name is ${name}" > "${name}".txt
echo "The description is: ${description}" >> "${name}".txt
echo "The version is: ${version}" >> "${name}".txt
done
For more details, see my blog post at https://blog.kellybrazil.com/2021/04/12/practical-json-at-the-command-line/
Thanks!