首页 > 解决方案 > 如何使用 JSON 中前一个值的最后一个数字继续新值?

问题描述

这是我的代码:

with open('res.json', 'r') as file1:
    json_data = json.load(file1) 
for g in json_data['groups']:
  try:
   for i, group in enumerate(g['resources']):
     group['slot'] = i 

  except:
      continue


with open("RES_Edited.JSON", 'w') as json_edited:
     json.dump(json_data, json_edited, indent = 1)

它使每个插槽都像插槽:1,插槽:2,插槽:3,这很棒。但是在 g['resources'] 的下一个孩子中,它又像 slot: 1, slot: 2, slot 3 一样重新开始。我希望它会从前一个孩子的最后一个数字继续。喜欢:插槽:4,插槽:5 ...

谢谢!

标签: pythonarraysjsonpython-3.x

解决方案


为什么不在整个代码中使用一个变量,而不是像下面这样的 for 循环:

with open('res.json', 'r') as file1:
    json_data = json.load(file1) 
i = 1
for g in json_data['groups']:
  try:
   for group in g['resources']:
     group['slot'] = i
     i += 1 

  except:
      continue

with open("RES_Edited.JSON", 'w') as json_edited:
     json.dump(json_data, json_edited, indent = 1)

推荐阅读