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

求助:如何用Python按条件修改JSON文件属性值(含报错代码)

Python修改JSON文件属性的正确方法

问题背景

有如下结构的JSON文件,需要完成三个修改需求:

  • 当gender为1(代表女性)时,将pregnant改为true
  • 所有equipedOutfit的id统一改为JobinsonsJersey
  • 所有equipedWeapon的id统一改为PlasmaThrower_DragonsMaw

JSON文件内容:

{
    "dwellers": [
        {
            "serializeId": 1,
            "name": "Kathleen",
            "lastName": "Hall",
            "gender": 1,
            "pregnant": false,
            "babyReady": false,
            "equipedOutfit": {
                "id": "jumpsuit",
                "type": "Outfit",
                "hasBeenAssigned": false,
                "hasRandonWeaponBeenAssigned": false
            },
            "equipedWeapon": {
                "id": "Fist",
                "type": "Weapon",
                "hasBeenAssigned": false,
                "hasRandonWeaponBeenAssigned": false
            }
        },
        {
            "serializeId": 2,
            "name": "MS",
            "lastName": "1",
            "gender": 2,
            "pregnant": false,
            "equipedOutfit": {
                "id": "JobinsonsJersey",
                "type": "Outfit",
                "hasBeenAssigned": false,
                "hasRandonWeaponBeenAssigned": false
            },
            "equipedWeapon": {
                "id": "PlasmaThrower_DragonsMaw",
                "type": "Weapon",
                "hasBeenAssigned": false,
                "hasRandonWeaponBeenAssigned": false
            }
        },
        {
            "serializeId": 3,
            "name": "WSLD",
            "lastName": "1",
            "gender": 2,
            "pregnant": false,
            "babyReady": false,
            "equipedOutfit": {
                "id": "JobinsonsJersey",
                "type": "Outfit",
                "hasBeenAssigned": false,
                "hasRandonWeaponBeenAssigned": false
            },
            "equipedWeapon": {
                "id": "PlasmaThrower_DragonsMaw",
                "type": "Weapon",
                "hasBeenAssigned": false,
                "hasRandonWeaponBeenAssigned": false
            }
        }
    ]
}

原代码的错误点

  1. 层级访问错误:json.load(file)返回的是顶层字典,直接循环这个字典会遍历键名(比如"dwellers"),而非数组里的居民对象,应该循环data["dwellers"]数组。
  2. 布尔值处理错误:JSON中的false/true在Python中是布尔值False/True,原代码用字符串比较object["pregnant"] == "false"完全错误。
  3. 赋值运算符错误:原代码用==(比较运算符)替代=(赋值运算符),无法完成属性修改。
  4. 文件操作错误:dwellers是字典对象,不是文件句柄,调用dwellers.close()会报错;且修改后未将数据写回文件。
  5. 循环终止错误:使用break会在修改第一个符合条件的对象后停止循环,无法实现“所有对象”的修改需求。

正确实现代码

将三个需求合并到一个函数中,一次读取修改后写回,效率更高:

import json

def modify_dwellers():
    # 读取JSON文件
    with open('./mindweller.json', 'r') as file:
        data = json.load(file)
    
    # 遍历所有居民对象
    for dweller in data["dwellers"]:
        # 需求1:女性居民设置pregnant为True
        if dweller["gender"] == 1:
            dweller["pregnant"] = True
        
        # 需求2:统一装备服装ID
        if dweller["equipedOutfit"]["id"] != "JobinsonsJersey":
            dweller["equipedOutfit"]["id"] = "JobinsonsJersey"
        
        # 需求3:统一装备武器ID
        if dweller["equipedWeapon"]["id"] != "PlasmaThrower_DragonsMaw":
            dweller["equipedWeapon"]["id"] = "PlasmaThrower_DragonsMaw"
    
    # 将修改后的数据写回文件
    with open('./mindweller.json', 'w') as file:
        json.dump(data, file, indent=4)

modify_dwellers()

代码说明

  • 通过data["dwellers"]获取居民数组,遍历每个居民对象完成修改。
  • 布尔值直接用True/False赋值,无需加引号。
  • 使用with语句自动管理文件句柄,无需手动调用close()。
  • 修改完成后用json.dump()将数据写回文件,indent=4保证JSON格式美观易读。
  • 移除不必要的break,确保所有符合条件的对象都被修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 10:52:50