I have the following data that I already insert in a file called file.json
:
{
"ip": "1.1.1.1",
"tested_count": 17,
"last_scan_date": "1673169149"
}
{
"ip": "1.1.1.1",
"tested_count": 17,
"last_scan_date": "1673169159"
}
{
"ip": "1.1.1.1",
"tested_count": 10,
"last_scan_date": "1673169326"
}
To be specific, this is how I added it using jq every time I run the script.sh
:
#!/bin/bash
# I run this script 3 times to insert into file.json:
#./script.sh 1.1.1.1 17
#./script.sh 1.1.1.1 17
#./script.sh 1.1.1.1 10
OUTPUT='file.json'
JSON_OUTPUT='data:{}'
IP="$1"
TEST_COUNT="$2"
JSON_OUTPUT=$(jq
--arg ip "${IP}"
--argjson tested_count "${TEST_COUNT}"
--arg last_scan_date "$(date +%s)"
'{ip: $ip, tested_count: $tested_count, last_scan_date: $last_scan_date}' <<<"${JSON_OUTPUT}")
# Write the output to the file
echo "${JSON_OUTPUT}" >>"${OUTPUT}"
Now, based on the output from file.json
it looks like it is not a valid json. So, my aim is to transform that into a valid json that looks like below:
{
"data": [
{
"ip": "1.1.1.1",
"tested_count": 17,
"last_scan_date": "1673169149"
},
{
"ip": "1.1.1.1",
"tested_count": 17,
"last_scan_date": "1673169159"
},
{
"ip": "1.1.1.1",
"tested_count": 10,
"last_scan_date": "1673169326"
}
]
}
I have seen an example of this here but the example shown there is using a looping method which is not necessary in my case as my json data is dynamically added each time the script.sh
above run.
What I have tried so far is using an update inputs
filter like this but obviously, this does not fix the json as a valid syntax.
echo "$json_query" | jq -n '.data |= [inputs]' >> file.json
2
Answers
You can you
sed
:Doing it properly with
jq
.I added lots of comments for both the shell and the jq script parts.
Don’t hesitate to question me in comments if something is unclear, anyway. That would be preferable to blindly copying code.