Issue
I can create a json object with an array using jq like this
echo '{"input":{"names":[]}}' | jq --arg val "alice" '.input.names[0] += $val'| jq --arg val "bob" '.input.names[1] += $val'
which gives
{
"input": {
"names": [
"alice",
"bob"
]
}
}
Now I want to recreate this in a shell script where "names" come from a shell array
#!/bin/sh
names=( alice bob )
ITER=0
for i in "${names[@]}"
do
echo '{"input":{"names":[]}}' | jq --arg val "$i" '.input.names[$ITER] += $val'
echo ${I} ${ITER}
ITER=$(expr $ITER + 1)
done
but I run into
jq: error: $ITER is not defined at <top-level>, line 1:
.input.names[$ITER] += $val
jq: 1 compile error
0
jq: error: $ITER is not defined at <top-level>, line 1:
.input.names[$ITER] += $val
jq: 1 compile error
1
Solution
You could get rid of the shell loop and use one jq
call:
names=( alice bob )
jq -n --arg names "${names[*]}" '{"input": {"names": ($names / " ") } }'
or
names=( alice bob )
printf '%s\0' "${names[@]}" |
jq -sR '(. / "\u0000") as $names | { "input": { "names": $names } }'
Answered By - Fravadona Answer Checked By - Mary Flores (WPSolving Volunteer)