[英]How to modify a JSON file using Python without losing comments in the file
[英]How to modify an element of array in file.json using Python?
我正在制作一个 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"
}
]
我测试了您的代码,它正确地向 JSON 添加了一个新条目并更改了特定 ID 的 gw_status。
用 Python 3.7.4 测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.