I have a bash array that I want to convert to json and write to file. Suppose it is
<code>my_strings=("hello" "world")
</code>
<code>my_strings=("hello" "world")
</code>
my_strings=("hello" "world")
I have managed to convert it to json and write to file with:
<code>for f in "${my_strings[@]}"; do printf '%s' "$f" | jq -R -s .; done | jq -s >> test_.json
</code>
<code>for f in "${my_strings[@]}"; do printf '%s' "$f" | jq -R -s .; done | jq -s >> test_.json
</code>
for f in "${my_strings[@]}"; do printf '%s' "$f" | jq -R -s .; done | jq -s >> test_.json
and the output resulting file looks like:
<code>[
"hello",
"world"
]
</code>
<code>[
"hello",
"world"
]
</code>
[
"hello",
"world"
]
However, the output I would like to have is
<code>{
"strings_":
[
"hello",
"world"
]
}
</code>
<code>{
"strings_":
[
"hello",
"world"
]
}
</code>
{
"strings_":
[
"hello",
"world"
]
}
I’ve tried prepend and append the graphs and the key like this:
<code>printf '{nt"strings_":n' > test_.json; for f in "${strings[@]}"; do printf '%s' "$f" | jq -R -s .; done | jq -s >> test_.json; printf "}n" >> test_.json
</code>
<code>printf '{nt"strings_":n' > test_.json; for f in "${strings[@]}"; do printf '%s' "$f" | jq -R -s .; done | jq -s >> test_.json; printf "}n" >> test_.json
</code>
printf '{nt"strings_":n' > test_.json; for f in "${strings[@]}"; do printf '%s' "$f" | jq -R -s .; done | jq -s >> test_.json; printf "}n" >> test_.json
but the resulting indentation is not good.
Is there a better way to do this?