如何用Python更新已有JSON文件?含特定字段修改场景
如何更新JSON中的指定字段并写回文件
现有代码与数据结构
读取JSON文件的代码
f = open("data.json", "r") data = np.array(json.loads(f.read()))
数据结构示例
[ { "symbol" : "NZDCHF", "timeframe" : [ {"tf":"H4","x1":0,"y1":0,"x2":0,"y2":0}, {"tf":"H1","x1":0,"y1":0,"x2":0,"y2":0}, {"tf":"M30","x1":0,"y1":0,"x2":0,"y2":0}, {"tf":"M15","x1":0,"y1":0,"x2":0,"y2":0}, {"tf":"M5","x1":0,"y1":0,"x2":0,"y2":0} ] }, { "symbol" : "AUDCHF", "timeframe" : [ {"tf":"H4","x1":0,"y1":0,"x2":0,"y2":0}, {"tf":"H1","x1":0,"y1":0,"x2":0,"y2":0}, {"tf":"M30","x1":0,"y1":0,"x2":0,"y2":0}, {"tf":"M15","x1":0,"y1":0,"x2":0,"y2":0}, {"tf":"M5","x1":0,"y1":0,"x2":0,"y2":0} ] } ]
查找指定内容的代码
selected = np.array([el for el in data if el["symbol"] == 'AUDCHF']) rect = selected[0]['timeframe'][4]
字段更新与写回步骤
1. 更新指定字段值
rect是对原data中字典的直接引用,修改它的键值对会同步更新原数据:
# 替换为你需要的目标数值 rect['x1'] = 100 rect['y1'] = 200 rect['x2'] = 300 rect['y2'] = 400
2. 处理数据格式(解决numpy序列化问题)
JSON无法直接序列化numpy数组,需要先转换为普通Python列表:
data_list = data.tolist()
3. 写入更新后的JSON文件
用with语句自动管理文件开闭,indent=4让输出的JSON格式化,可读性更强:
import json with open("data.json", "w") as f: json.dump(data_list, f, indent=4)
优化建议
没必要将JSON读取结果转为numpy数组,直接用Python列表即可简化操作:
import json # 优化读取逻辑 with open("data.json", "r") as f: data = json.load(f) # 优化查找逻辑 selected = [el for el in data if el["symbol"] == 'AUDCHF'][0] rect = selected['timeframe'][4] # 更新字段 rect['x1'] = 100 rect['y1'] = 200 rect['x2'] = 300 rect['y2'] = 400 # 直接写入文件 with open("data.json", "w") as f: json.dump(data, f, indent=4)
内容的提问来源于stack exchange,提问作者joenpc npcsolution
相关产品推荐
相关产品推荐

