jq cast result into bash array

Tags: bash jq
By : AleIla
Source: Stackoverflow.com
Question!

next to my attempt to parse a JSON response from curl using bash I now decided to give a try with jq. I have checked the documentation but I could not find a way to iterate trough the elements and "do" something.

Here's an idea on what I am trying to achieve, cast the result from jq into an array, (it doesn't work)

__json=$($omd_response | ~/local-workspace/bash/jq -r '[.]')
for x in "${__json[@]}"
do
  echo "-metadata" $x
done

Any other idea is much appreciated. Thanks

By : AleIla


Answers

This:

declare -a things
things=($(jq tostring myfile.json) )
for x in "${things[@]}"; do
    echo "-metadata" "$x"
done

almost works. It splits things on whitespace.

This works:

declare -a things
OIFS=$IFS
IFS= things=($(jq -r 'tojson|tostring' myfile.json) )
IFS=$OIFS
for x in "${things[@]}"; do
    echo "-metadata" "$x"
done

Really, we need a JSON-aware shell... Something like ksh93's compound variables, but JSON-compatible.



This video can help you solving your question :)
By: admin