我如何用JSON中先前值的最后一个数字继续新值?

问题描述 投票:1回答:1

这是我的代码:

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']的下一个子级中,它又像插槽:1,插槽:2,插槽3一样开始。我希望它从上一个子级的最后一个数字继续。如:广告位:4,广告位:5 ...

谢谢!

python arrays json python-3.x
1个回答
1
投票

为什么不在整个代码中使用一个变量,而不是像下面这样的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)

0
投票

对当前代码的最小更改。只需在循环范围之外添加一个变量,然后使用range而不是enumerate

current_child = 0

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

  except:
      continue


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

© www.soinside.com 2019 - 2024. All rights reserved.