【问题标题】:How to modify an element of array in file.json using Python?如何使用 Python 修改 file.json 中的数组元素?
【发布时间】:2021-12-16 06:21:42
【问题描述】:

我正在制作一个 discord.py 赠品机器人

我试图保存赠品的状态(正在进行或结束)。

但我不知道如何修改数组

这是代码:-

  with open ('gw.json') as json_file:
    data = json.load(json_file)

    new_gw = {
      'gw_id': f"{react.id}",
      'gw_prize': prize,
      'gw_status': "ongoing"
    }

  data.append(new_gw)

  with open('gw.json', 'w') as j:
    json.dump(data, j, indent=3)

我试过这样做,但没有成功

with open('gw.json') as gw_file:
      data = json.load(gw_file)
      for x in data:
        if x['gw_id'] == msgid:
          x['gw_status'] = "ended"

  with open('gw.json', 'w') as j:
    json.dump(data, j)

也尝试过谷歌搜索,但对我没有任何帮助

我想要做的是将“gw_status”从正在进行更改为已结束 来自:-

[
   {
      "gw_id": "904772439827951657",
      "gw_prize": "4",
      "gw_status": "ongoing"
   }
]

到这里:-

[
   {
      "gw_id": "904772439827951657",
      "gw_prize": "4",
      "gw_status": "ended"
   }
]
``` on the existing entry that was added before

【问题讨论】:

  • 你好,你可以把与问题无关的部分去掉。如果您能提供可重现的代码,我们会更容易提供帮助。

标签: python json discord discord.py


【解决方案1】:

我测试了您的代码,它正确地向 JSON 添加了一个新条目并更改了特定 ID 的 gw_status。
使用 Python 3.7.4 测试。

【讨论】:

  • 那么如何更改现有条目的状态
  • 我想更改现有条目 'gw_status' = "ended"
  • 它应该更改所有现有条目,因为整个 json 文件会再次打开,并且所有条目都会被检查为获胜者。
猜你喜欢
  • 2013-01-21
  • 2018-04-20
  • 2020-07-04
  • 1970-01-01
  • 1970-01-01
  • 2017-01-04
  • 1970-01-01
  • 2023-02-15
  • 1970-01-01
相关资源
最近更新 更多