You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python替换JSON文件中指定条目的对应字段取值

Python修改JSON条目状态字段问题解决方案

错误点

  • 核心逻辑错误:更新gw_status的代码错误引用了不存在的字段x['completed'],你的JSON结构中单个条目仅包含gw_id、gw_prize、gw_status三个字段,没有completed字段,直接赋值为字符串"completed"即可,不需要调用replace方法。
  • 缩进错误:你贴出的代码中data.append(new_gw)、第一个写入文件的with块的缩进层级和上层读取文件的with块不匹配,实际运行会触发缩进错误。
  • 缺省兼容配置(非必现错误):如果你的JSON包含中文内容,读写文件时没有指定encoding='utf-8'、导出时没有加ensure_ascii=False会出现乱码问题。
  • 漏导模块(非必现错误):如果代码开头没有导入json模块,运行会直接报错。

修正后的完整代码

import json

# 新增gw条目部分
with open('gw.json', 'r', encoding='utf-8') 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', encoding='utf-8') as j:
    json.dump(data, j, indent=4, ensure_ascii=False)

# 后续修改指定条目状态为completed部分
msgid = "904905768149590086" # 替换为你实际需要匹配的gw_id值
with open('gw.json', 'r', encoding='utf-8') as jsonFile:
    data = json.load(jsonFile)
    for x in data:
        if x['gw_id'] == f"{msgid}":
            # 直接赋值为目标状态即可,无需调用replace方法
            x['gw_status'] = "completed"

with open('gw.json', 'w', encoding='utf-8') as jsonFile:
    json.dump(data, jsonFile, indent=4, ensure_ascii=False)

内容的提问来源于stack exchange,提问作者Yash Verma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 14:06:03