Join an array to create JSON dynamically
9,002
Solution 1
With jo
, which makes it easy to generate JSON on the command line:
$ jo -p key1="$value1" key2="$value2"
{
"key1": "foo",
"key2": "bar"
}
or, depending on what you want the end result to be,
$ jo -a -p "$(jo key1="$value1")" "$(jo key2="$value2")"
[
{
"key1": "foo"
},
{
"key2": "bar"
}
]
Note that jo
will also properly encode the values in the strings $value1
and $value2
.
Solution 2
With perl
:
$ perl -MJSON -e 'print JSON->new->pretty(1)->encode({@ARGV})' -- "${arr[@]}"
{
"key2" : "bar",
"key1" : "foo"
}
Author by
Alexander Mills
Updated on September 18, 2022Comments
-
Alexander Mills over 1 year
Declaring JSON in bash is kind of annoying because you have to escape a lot of characters.
Say I have an array like this:
value1="foo" value2="bar" arr=("key1" "$value1" "key2" "$value2")
Is there a way to somehow join the array with ":" and "," characters.
The only thing I can think of is a loop where you add the right characters, something like this:
data=""; for i in "${arr[@]}"; do data="$data\"$i\"" done