python - 如何使用 JSON 中前一个值的最后一个数字继续新值?

标签 python arrays json python-3.x

这是我的代码:

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)

它使每个插槽都像 slot: 1、slot: 2、slot: 3 一样,这很棒。但在 g['resources'] 的下一个子项中,它再次开始,如 slot: 1、slot: 2、slot 3。我希望它将从上一个子项的最后一个数字继续。 例如:插槽:4、插槽:5...

谢谢!

最佳答案

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

关于python - 如何使用 JSON 中前一个值的最后一个数字继续新值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59118559/

相关文章:

python - 重写所有 svn :externals in repository trunk 的脚本/实用程序

python - 如何解决 : InvalidArgumentError: Graph execution error?

java - 对于 ArrayList 中的每个项目替换为模式

android - 改造为 Android 中的请求制作空体

java - MySQL PHP JSON 空文本

python - 如何在 Python 3.0 中输出 Unicode 符号?

python - 我无法安装 Gevent

javascript - 检查数组中的每个元素是否都有特定值

java - 服务器类和客户端类 - 多维数组

javascript - 如何从对象中提取2字字段?