Python修改JSON的country字段遇报错:AttributeError与TypeError求解
解决JSON列表中修改字段的Python报错问题
问题背景
你有如下结构的JSON文件:
[{ "title": "Reference Addition", "ref_date": 20200110, "country": "ASIA", "ref_internal": "1", "ref_external": "1" }]
尝试用Python修改country字段值并保存,最初代码:
with open('myfile.json', 'r') as f: json_data = json.load(f) json_data['country'] = 'AFRICA' with open('myfile.json', 'w') as f: json.dump(json_data, f, indent=2)
出现错误:
AttributeError: module 'json' has no attribute 'tree'
修改代码后:
import json myfile = ('JSON\TRADE.json') with open (myfile, 'r') as myfile: json_data = json.load(myfile) json_data['country'] = 'AFRICA' json.tree.dump(json_data, indent=4) with open(myfile, 'w') as f: json.dump(json_data, f, indent=4)
遇到新错误:
File "c:\AUTOMATION\Data Creation\JSON\EDIT.py", line 7, in json_data['country'] = 'AFRICA' TypeError: list indices must be integers or slices, not str
错误原因
AttributeError错误:Python标准库的json模块没有tree属性,你错误使用了不存在的方法,完全不需要这个写法。TypeError错误:你的JSON根结构是列表(数组),json.load()加载后得到的json_data是列表类型,不能直接用字符串键'country'访问。列表需要用索引(比如[0])获取里面的字典元素,再修改对应字段。
正确解决代码
import json # 加载原JSON文件 with open('JSON\TRADE.json', 'r') as f: json_data = json.load(f) # 修改列表中第一个字典的country字段 json_data[0]['country'] = 'AFRICA' # 保存到新文件(避免覆盖原文件,可自定义文件名) with open('JSON\TRADE_modified.json', 'w') as f: json.dump(json_data, f, indent=2)
代码说明
- 用
json_data[0]获取列表中的第一个字典元素(因为你的JSON只有一个对象在列表里) - 修改完成后保存到新文件,防止误改原文件
- 保留
indent参数让输出的JSON格式更易读
内容的提问来源于stack exchange,提问作者user3130038
相关产品推荐
相关产品推荐

