create json from bash variable and associative array
Assuming that none of the keys or values in the "animals" array contains newline characters:
for i in "${!animals[@]}"do printf "%s\n%s\n" "${i}" "${animals[$i]}"done | jq -nR --arg oldMcD "$mcD" --arg eei "$eei" ' def to_o: . as $in | reduce range(0;length;2) as $i ({}; .[$in[$i]]= $in[$i+1]); {$oldMcD, $eei, onthisfarm: [inputs] | to_o}'
Notice the trick whereby {$x}
in effect expands to {(x): $x}
Using "\u0000" as the separator
If any of the keys or values contains a newline character, you could tweak the above so that "\u0000" is used as the separator:
for i in "${!animals[@]}"do printf "%s\0%s\0" "${i}" "${animals[$i]}"done | jq -sR --arg oldMcD "$mcD" --arg eei "$eei" ' def to_o: . as $in | reduce range(0;length;2) as $i ({}; .[$in[$i]]= $in[$i+1]); {$oldMcD, $eei, onthisfarm: split("\u0000") | to_o }'
Note: The above assumes jq version 1.5 or later.
You can reduce associative array with for loop and pipe it to jq
:
for i in "${!animals[@]}"; do echo "$i" echo "${animals[$i]}"done |jq -n -R --arg mcD "$mcD" --arg eei "$eei" 'reduce inputs as $i ({onThisFarm: [], mcD: $mcD, eei: $eei}; .onThisFarm[0] += {($i): (input | tonumber ? // .)})'