Issue
I have a JSON file called data.json with the following content:
{
"A": "10",
"BB": {
"m": "refresh",
"t": 1100,
"tt": 1,
"pp": 0,
"fp": 0
},
"ss": "1",
"ZZZ": {
"0": {
"np": 45,
"sh": "True",
"ni": 32,
"ft": "False",
"te": "True",
"t": 23,
"mm": 21
}
},
"nr": "564"
}
I want to a have bash script that does the following task. There is a for loop of i = 1 to 100 iterations. In the first iteration, only 0 in the value of "ZZZ" should be changed to the value of i which is 1. The new content should be written to data.json. In the second iteration, the content of data.json is read and only 1 in the value of "ZZZ" should be changed to the value of i which is 2 now and the new content should be written to data.json. This process executes to the end of the loop. I have the following script:
#!/bin/bash
# Input JSON file and output directory
input_file="data.json"
# Loop from i=1 to 100
for ((i=1; i<=100; i++)); do
# Copy the original JSON to a new file
cp "$input_file" "output.json"
# Modify the JSON file with jq
jq --argjson new_i "$i" '.ZZZ[$new_i] = .ZZZ[$i - 1] | del(.ZZZ[$i - 1])' "output.json" > "temp.json"
# Move the modified JSON back to the original file
mv "temp.json" "data.json"
done
When I run the script, I get the following error:
jq: 2 compile errors
jq: error: $i is not defined at <top-level>, line 1:
.ZZZ[$new_i] = .ZZZ[$i - 1] | del(.ZZZ[$i - 1])
My question is how to fix the error?
Thank you.
Solution
One way to achieve what you are looking for is as follows:
#!/bin/bash
for ((i=1; i<=100; i++)); do
jq '.ZZZ = {
'\"$i\"': {
"np": 45,
"sh": "True",
"ni": 32,
"ft": "False",
"te": "True",
"t": 23,
"mm": 21
}
}' "data.json" > "temp.json"
mv "temp.json" "data.json"
done
If you'd like to have distinct files after each write, you can change mv "temp.json" "data.json"
to mv "temp.json" "data_$i.json"
Answered By - Bsh Answer Checked By - Marie Seifert (WPSolving Admin)