I would like to convert an associative array in bash to a json hash/dict. I would prefer to use jq to do this as it is already a dependency and I can rely on it to produce w
You can initialize a variable to an empty object {}
and add the key/values {($key):$value}
for each iteration, re-injecting the result in the same variable :
#!/bin/bash
declare -A dict=()
dict["foo"]=1
dict["bar"]=2
dict["baz"]=3
data='{}'
for i in "${!dict[@]}"
do
data=$(jq -n --arg data "$data" \
--arg key "$i" \
--arg value "${dict[$i]}" \
'$data | fromjson + { ($key) : ($value | tonumber) }')
done
echo "$data"