I would like to add a number of key:value pairs to an existing JSON string. The values are passed as command line arguments to my script.
So far I’ve got this
data='{"update": { "labels": [] } }'
for label in "${@}";do
objJSON=$(printf '%sn' "{ "add": ${label} }" | jq -R . | jq -s .)
data=$(echo ${data} | jq --argjson jsonString "$objJSON" '.update.labels += $jsonString')
done
echo ${data} >output.txt
jq --color-output . output.txt
My output is this:
{
"update": {
"labels": [
"{ add: value1 }",
"{ add: value2 }"
]
}
}
but I’m trying to get this (note the quotes surrounding add
and each value):
{
"update": {
"labels": [
{ "add": "value1" },
{ "add": "value2" }
]
}
}
I can’t see where I’m going wrong – can anyone help please?
3
Answers
Since your
add
key is static, I’d only pass thevalue
of the item you want to add using the correct key as varibale.Then you can add it by doing
.. |= { $add }
:
Why not do everything in a single call to jq, using
--args "$@"
to transfer all arguments to jq, and therein the$ARGS.positional
array to reference them:Or, if you let jq also generate the initial document, it’s really just that one call:
Make sure to escape your key/value quotes:
Here is a Bash script that handles adding new objects to the update labels array.
Here is the usage: