You shouldn't write json the file inside of the loop, you should build a dictionary or list of dictionaries, then write that with json.dump()
import json
# initialize the dictionary
my_dict = {}
# loop to emulate your data structure
for i in range(10):
# assign a1 and a2
a1 = i
a2 = i ** 2 # just so the value is different than the key for demonstration
# set a1 as the key and a2 as the value
my_dict[a1] = a2
# use json.dump to write the file
with open('./square.json', 'w') as file:
json.dump(my_dict, file, indent=4)
Output (square.json):
{
"0": 0,
"1": 1,
"2": 4,
"3": 9,
"4": 16,
"5": 25,
"6": 36,
"7": 49,
"8": 64,
"9": 81
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…