Here's a way that doesn't need an extra step before to serialise the associative array:
jq -n '
$ARGS.positional|
. as $a|
(length/2) as $l|
[range($l)|{key:$a[.],value:$a[.+$l]}]|
from_entries' --args "${!myarray[@]}" "${myarray[@]}"
It should work even with newlines in the keys or values. The one caveat is that technically bash doesn't guarantee that ${!myarray[@]}
will output the keys in the same order that ${myarray[@]}
will output the values. It does do that in practice, and it's hard to imagine an implementation that wouldn't, but if you really want to be safe here's a variation on Inian's answer that should be safe to newlines. It also assembles a single object.
for key in "${!myarray[@]}"; do
printf "%s\0%s\0" "$key" "${myarray[$key]}"
done |
jq -sR '
split("\u0000")|
. as $elements|
[range(length/2)|{key:$elements[2*.],value:$elements[2*.+1]}]|
from_entries'