求助:如何用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 } } ] }
原代码的错误点
- 层级访问错误:
json.load(file)返回的是顶层字典,直接循环这个字典会遍历键名(比如"dwellers"),而非数组里的居民对象,应该循环data["dwellers"]数组。 - 布尔值处理错误:JSON中的
false/true在Python中是布尔值False/True,原代码用字符串比较object["pregnant"] == "false"完全错误。 - 赋值运算符错误:原代码用
==(比较运算符)替代=(赋值运算符),无法完成属性修改。 - 文件操作错误:
dwellers是字典对象,不是文件句柄,调用dwellers.close()会报错;且修改后未将数据写回文件。 - 循环终止错误:使用
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
相关产品推荐
相关产品推荐

