Python写入JSON文件时无法将数据存入指定x类别问题求助
解决Python向JSON文件指定数组添加数据的问题
问题说明
我是JSON新手,想通过Python把数据写入JSON文件的"x"数组里,但写入的内容总是出现在文件底部,没法加到指定数组中。
我的代码
x = open("x.json", "a", encoding="utf-8") x_r.write( ',\n{' '"id":' f'"{id}"' ', "name":' f'"{name}"' "}" )
期望的JSON结构
{ "x": [ {"id": "x", "name": "x"}, {"id": "x", "name": "x"} ] }
当前错误的JSON结构
{ "servers": [ ] } {"id": "x", "name": "x"}, {"id": "x", "name": "x"}
解决方法
直接用追加模式("a")写字符串会破坏JSON的语法结构,正确操作应该是先解析JSON为Python数据结构,修改后再重新写入:
修正后的代码
import json # 读取现有JSON文件内容并解析为字典 with open("x.json", "r", encoding="utf-8") as f: data = json.load(f) # 准备要添加的新数据项 new_data = {"id": id, "name": name} # id和name为你要传入的变量 # 将新数据追加到"x"数组中 data["x"].append(new_data) # 将更新后的字典重新写入JSON文件,保持格式美观 with open("x.json", "w", encoding="utf-8") as f: json.dump(data, f, indent=2, ensure_ascii=False)
额外处理:初始化文件或缺失的数组
如果JSON文件不存在,或者文件里没有"x"数组,需要先初始化结构:
import json import os file_path = "x.json" # 检查文件是否存在 if not os.path.exists(file_path): # 初始化基础结构 data = {"x": []} else: with open(file_path, "r", encoding="utf-8") as f: data = json.load(f) # 确保"x"数组存在 if "x" not in data: data["x"] = [] # 添加新数据 new_data = {"id": id, "name": name} data["x"].append(new_data) # 写入文件 with open(file_path, "w", encoding="utf-8") as f: json.dump(data, f, indent=2, ensure_ascii=False)
关键说明
- 用
json.load()和json.dump()处理JSON文件,能保证语法的正确性,避免手动拼接字符串导致的结构错误。 indent=2让输出的JSON保持缩进格式,和期望结构一致。ensure_ascii=False支持写入中文字符,不会转义为Unicode编码。
内容的提问来源于stack exchange,提问作者Zextrex33
相关产品推荐
相关产品推荐

