I need to loop through a dictionary and append records to a json object file option.json
the code I have is
for K in "${!MYMAP[@]}"; do
opt="{
"OptionName":"${K}",
"Value":"${MYMAP[$K]}"
},"
echo $opt >> option.json
done
But this produce option.json as below
{
"OptionName": "name",
"Value": "test"
},
{
"OptionName": "age",
"Value": "13"
}
How do i make the option.json a json object and appending each {} inside the object, so my option.json would look like below
[
{
"OptionName": "name",
"Value": "test"
},
{
"OptionName": "age",
"Value": "13"
}
]
2
Answers
If you omit the trailing comma in the initial production, you get a stream of inputs that jq can collect into an array using the
--slurp
(or-s
) flag:However, you can also have jq do the JSON composition in the first place, guaranteeing valid JSON encoding even with challenging values (such as double quotes, etc.). For example, I’d use the
--args
option to import the bash array’s keys and values as positional parameters, and the$ARGS
builtin to access them:As @oguz pointed out, newer versions of bash can also expand arrays to their keys and values in our desired alternating order by using
"${mymap[@]@k}"
. The full jq filter would then just read:Sure it’s better to use
jq
if you work with json but in case whenjq
is not availableprintf
can be used, like this:Here is I’m using
jq
to validate the result:Note this syntax
${items%,*}
it will print$items
without last comma which is crucial for json.