1

I have script

#!/bin/bash
ARR=("a" "b")

collection_init_msg=$( jq -n --arg arr $ARR '{arr: [$arr]}')

echo some command "$collection_init_msg" 

that should convert the ARR and print it as a JSON array.

Current result

some command { "arr": [ "a" ] }

What I want is:

some command { "arr": [ "a", "b" ] }

1
  • 1
    $ARR is exactly the same as ${ARR[0]}. You can't pass the entire array as a single value; you can only pass a single string built from the elements of the array. Commented Dec 2, 2022 at 23:41

1 Answer 1

5
#!/bin/bash
ARR=("a" "b")

collection_init_msg=$( jq -nc '{arr: $ARGS.positional}'  --args "${ARR[@]}"  )

echo "$collection_init_msg" 

In answer to the supplementary question in the comment: one could do worse than:

jq -n --argjson a1 $(jq -nc '$ARGS.positional' --args "${A1[@]}") '
  {$a1, a2: $ARGS.positional}' --args "${A2[@]}"
Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to submit multiple arrays? E.g. #!/bin/bash ARR1=("a" "b") ARR2=("1" "2") and have an output like { "arr1": [ "a", "b" ], "arr2" ["1", "2"] }
@tot - See addendum.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.