如何为Pandas导出的Records格式JSON添加顶层对象?
问题描述
现有代码将DataFrame导出为JSON数组格式:
json_data = df.to_json(orient='records') parser = json.loads(json_data) json_data = json.dumps(parser, indent=4, ensure_ascii=False)
输出格式为:
[ { "att1": "321", "att2": "abc", "att3": "cba" }, { "att1": "abc", "att2": "cba", "att3": "123" } ]
希望转为包含top键的JSON对象,期望输出:
{ "top": [ { "att1": "321", "att2": "abc", "att3": "cba" }, { "att1": "abc", "att2": "cba", "att3": "123" } ] }
询问能否通过Pandas的to_json函数实现,或需要手动处理,以及具体修改方式。
解决方案
两种方式都可以实现,推荐手动构造字典的方式,更简洁高效:
方法一:手动构造顶层结构(推荐)
直接把解析后的数组放到包含top键的字典里再序列化,无需依赖Pandas特殊参数:
# 修改后的完整代码 json_data = df.to_json(orient='records') parser = json.loads(json_data) # 构造带顶层键的字典 result_dict = {"top": parser} # 序列化生成目标JSON json_data = json.dumps(result_dict, indent=4, ensure_ascii=False)
方法二:通过Pandas构造嵌套结构(可选)
可以将原DataFrame包装成嵌套结构后导出,但步骤相对冗余:
import pandas as pd # 构造包含top键的嵌套DataFrame nested_data = pd.DataFrame({"top": [df.to_dict('records')]}) # 导出为目标格式的JSON json_data = nested_data.to_json(orient='columns', indent=4, ensure_ascii=False)
内容的提问来源于stack exchange,提问作者pyth0nEiken
相关产品推荐
相关产品推荐

