我的代码
with open('res1536.json', 'r') as json_file:
json_data = json.load(json_file)
for group in json_data['resources']:
group['slot'] = 0
group['slot'] += 1
with open("RES_Edited.JSON", 'w') as json_edited:
json.dump(json_data, json_edited, indent = 1)
但是它保存所有的插槽,例如“ slot”:1 我希望它将是“插槽”:1 “广告位”:2 “广告位”:3 ...
谢谢!
答案 0 :(得分:0)
在循环时进行计数的一个好方法是enumerate
。文件:http://book.pythontips.com/en/latest/enumerate.html
with open('res1536.json', 'r') as json_file:
json_data = json.load(json_file)
for i, group in enumerate(json_data['resources']):
group['slots'] = i
with open("RES_Edited.JSON", 'w') as json_edited:
json.dump(json_data, json_edited, indent = 1)
您可以明确地执行以下操作:
i = 0
for group in json_data['resources']:
group['slots'] = i
i += 1