I have an existing key.json file that looks like this:
key.json
{
"resstart": 1700839261,
"resend": 1700839965,
"resop": "SUCCESS",
"resurl": "http://xxxx/",
"ressummary": {
"value": 1,
"expect": 0,
"tool": "abc"
},
}
I need to add the below section in my json under ressummary
"Check": [
{
"Check": "["A_DOG","A_CAT", "A_HORSE"]",
"code": "C/C++"
}
]
So the final json file should look like:
{
"resstart": 1700839261,
"resend": 1700839965,
"resop": "SUCCESS",
"resurl": "http://xxxx/",
"ressummary": {
"value": 1,
"expect": 0,
"tool": "abc"
"Check": [
{
"Check": "["A_DOG","A_CAT", "A_MOUSE", "A_HORSE"]",
"code": "C/C++"
}
]
},
}
I am using shell script to generate the above json. My code is:
name="key"
ccheck=("A_DOG" "A_CAT" "A_MOUSE" "A_HORSE")
echo "{"Check": { "Check": "['$ccheck[@]']", "code": "C/C++"}}" >> $name.json
sed -i "s/'/"/g" $name.json
cat $name.json
I am getting the below error:
parse error: jq 1 compile error
Can anyone tell me how I can get the desired json file ? I would like to do this with jq. Is there a better way to do this? I have tried define ccheck as a string and array, but i am not getting the "" and , either.
3
Answers
To achieve the desired result in your JSON file using jq, you’ll need to modify your approach slightly.
printf '%sn' "${ccheck[@]}" | jq -R . | jq -s .
: This part of the script converts the bash arrayccheck
into a JSON array.jq -R
reads raw strings (one per line) andjq -s
slurs them into an array.jq
command then adds this array under the "Check" key in "ressummary". We usejoin(",")
to convert the array into a string representation, which includes the required quotes.temp.json
) and then renamed to your original file name. This is a safer way to modify files withjq
.Run this script in the directory where your
key.json
file is located. It will add the specified section to your JSON file as per your requirement.Here is my shell with jq
input.json
insert.json
The result:
Here is explain.
I am only explain the first statement I given.
The correct
ressummary
we need:So basically we just merge the insert.json to the
ressummary
.using this statement will make a json looks like this.
And this should be place under the
ressummary
Using this statement will get a json looks like this
then we can merge it to the original input.
use parentheses for priority arithmetic
.[0].ressummary * .[1] | {ressummary:.}
PS: Using
-s
with jq will make jq read multiple input as array like this:BUT I STILL RECOMMEND USING PYTHON TO HANDLE THE JSON.
This is how you import data using jq:
--arg varname "value"
to have access to a jq variable$varname
set to the stringvalue
--args "value1" "value2" …
(as last arguments) to set the builtin$ARGS.positional
to the string array["value1", "value2", …]
.ressummary.Check = […]
to set theCheck
field to an array as defined (or.ressummary.Check += […]
to append to that array)