Python保存JSON至文件时结构不符合预期的问题求助
问题描述
预期数据结构:
Key1: [Key2:[{},{},...{}]]
使用的代码:
dict_={} dict_['Key2']=all_items dict_fin={} dict_fin['Ke1']=[dict_] # 注意此处拼写错误:Ke1应为Key1 df=pd.DataFrame(dict_fin) df.to_json(filepath, orient="records",lines=True)
期望生成的JSON格式:
{ "Key1": [{"Key2" : [{},{},...,{}]}] }
实际得到的JSON格式:
{ "Key1": {"Key2" : [{},{},...,{}]} }
解决方案
问题出在两个核心点:
- 代码存在拼写错误:
dict_fin['Ke1']应改为dict_fin['Key1'],否则最终JSON的键名会不符合预期。 - 用pandas的DataFrame处理这种嵌套JSON结构不合适——pandas是为表格型数据设计的,它会自动扁平化嵌套的列表结构,导致外层数组包裹丢失。
直接用Python原生json模块写入文件即可保留预期的嵌套层级,修正后的代码如下:
import json dict_ = {} dict_['Key2'] = all_items dict_fin = {} dict_fin['Key1'] = [dict_] # 修正拼写错误,保留列表包裹 with open(filepath, 'w', encoding='utf-8') as f: json.dump(dict_fin, f, indent=2) # indent参数用于格式化输出,可按需调整
如果需要实现原代码中lines=True的单行JSON格式,可改用json.dumps生成字符串后写入:
with open(filepath, 'w', encoding='utf-8') as f: f.write(json.dumps(dict_fin))
内容的提问来源于stack exchange,提问作者Nikky Leed
相关产品推荐
相关产品推荐

