Home > Back-end >  jq pass an array that should be converted into json array
jq pass an array that should be converted into json array

Time:12-03

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" ] }

CodePudding user response:

#!/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[@]}"
  • Related