The question is exactly the opposite of Constructing a json hash from a bash associative array. Given the following JSON:
{
"a": "z",
"b": "y",
"c": "x"
}
I would like to have an associative Bash array.
The question is exactly the opposite of Constructing a json hash from a bash associative array. Given the following JSON:
{
"a": "z",
"b": "y",
"c": "x"
}
I would like to have an associative Bash array.
A NUL-delimited stream is the safest approach:
input='{"a":"z","b":"y","c":"x"}'
declare -A data=()
while IFS= read -r -d '' key && IFS= read -r -d '' value; do
data[$key]=$value
done < <(jq -j 'to_entries[] | (.key, "\u0000", .value, "\u0000")' <<<"$input")
Note the use of jq -j
, which suppresses quoting (like -r
), but also suppresses the implicit newline between items, letting us manually insert a NUL instead.
See the discussion in https://github.com/stedolan/jq/issues/1271 (a ticket explicitly requesting a NUL-delimited output mode), wherein this idiom was first suggested.
You can do it like this :
while IFS=':' read k v
do
dict[$k]="$v"
done <<< "$( sed -E "s/(\"|,|{|})//g; /^ *$/d; s/^ *//g" input.txt )"
echo "The value of key 'a' is : ${dict[a]}"
Hope it helps you!