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

如何使用Python修改JSON文件中的指定字段值?

Python 修改 JSON 文件内容的正确实现方法

问题背景

原始 JSON 文件内容:

{
  "roll no": "210",
  "school": "DAP",
  "city": "Delhi",
  "hobbies": [
    {
      "dance": "yes"
    },
    {
      "singing": "yes"
    },
    {
      "travel": "yes"
    }
  ]
}

需求:

  • 将 "roll no" 的值改为 "211"
  • 将 "hobbies" 数组中 "singing" 和 "travel" 的值改为 "no"

用户尝试的错误代码:

with open("student.json","r") as file:
    data=json.load(file)
    data["roll no"]= "211"
    
    for x in data:
        x["hobbies"]["singing"]="no"
        x["hobbies"]["travel"]="no"

            
        with open("student.json","w") as file:

        json.dump(data,file,indent=4)

问题:仅成功修改了 "roll no",无法修改 hobbies 中的值。期望输出:

{
  "roll no": "211",
  "school": "DAP",
  "city": "Delhi",
  "hobbies": [
    {
      "dance": "yes"
    },
    {
      "singing": "no"
    },
    {
      "travel": "no"
    }
  ]
}

错误原因分析

  • 遍历对象错误:for x in data 实际遍历的是 JSON 字典的键(如 "roll no"、"school"),而非 hobbies 数组里的元素,导致无法正确访问到目标字典。
  • 数组元素访问方式错误:hobbies 是数组,每个元素是独立的字典,不能直接通过 x["hobbies"]["singing"] 访问,需要遍历数组内的每个字典。
  • 文件写入缩进错误:写入文件的代码缩进错误,且不应放在循环内部,应在所有数据修改完成后统一写入。

正确实现代码

import json

# 读取 JSON 文件
with open("student.json", "r") as file:
    data = json.load(file)

# 修改 roll no 的值
data["roll no"] = "211"

# 遍历 hobbies 数组,修改指定键的值
for hobby in data["hobbies"]:
    # 判断当前字典的键是否为 singing 或 travel
    if "singing" in hobby:
        hobby["singing"] = "no"
    elif "travel" in hobby:
        hobby["travel"] = "no"

# 将修改后的数据写入文件
with open("student.json", "w") as file:
    json.dump(data, file, indent=4)

说明

  • 先通过 json.load() 读取文件内容为 Python 字典,修改完成后再用 json.dump() 写入文件。
  • 遍历 data["hobbies"] 数组中的每个字典,通过判断键名来修改对应的值,确保精准修改目标项。
  • 写入文件的操作放在所有修改完成后,避免多次重复打开文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 12:35:18