stringify bash array to json string

62 views Asked by At

I'm new to bash and I have a bash script with a variable that is an array called 'output'

I'd like to convert the bash array to a JSON string. for example:

original array: output = ['one', 'two']

desired output: '["one","two"]'

I have tried the following:

"$(jq -c -n '$ARGS.positional' --args "${output[@]}")"

but that seems to wrap the array inside another set of square brackets:

'["[\"one\",\"two\"]"]'

which is not what I want.

also, I'd like to assign the JSON string to a variable.

I also saw that I can do this:

echo '{"foo" : "bar"}' | jq -R .

but I dont know how to use my variable 'output' instead of the hard-coded object. Also, not sure how to assign the result of that to a variable

EDIT

here's the bash script:

service_list_json="$(jq -c -n '$ARGS.positional' --args "${output[@]}")"

EDIT 2

ok, I think I might be seeing where the issue is. the original array looks like this:

'["one","two"]'

i'm guessing the extra set of quotes around the array are causing it to be treated like a string?

1

There are 1 answers

0
choroba On BEST ANSWER

The $output is a string, not an array.

To declare a bash array, you need the following syntax:

output=(one two)

It then provides the expected result.

service_list_json=$(jq -c -n '$ARGS.positional' --args "${output[@]}")
echo "$service_list_json"

Output:

["one","two"]