如何用Python将多行列ID数据的JSON转换为每行单个ID格式
JSON格式转换解决方案
针对你需要将嵌套JSON转换为每个条目单独一行的需求,以下是两种实用的Python实现方案,同时解决pd.read_json无法读取原文件的问题:
方案1:输出JSON Lines格式(每行一个独立条目)
这种格式是每行一个完整的JSON对象,pandas可直接用lines=True参数读取,完全匹配你要的第一种输出格式:
import json # 读取原始JSON文件 with open("input.json", "r", encoding="utf-8") as infile: raw_data = json.load(infile) # 提取responses列表,每行写入一个条目 with open("output.jsonl", "w", encoding="utf-8") as outfile: for entry in raw_data["responses"]: json.dump(entry, outfile) outfile.write("\n")
使用pandas读取转换后的文件:
import pandas as pd df = pd.read_json("output.jsonl", lines=True)
方案2:保留外层responses结构,条目单独换行
如果需要保留原有的外层responses数组结构,同时让每个ID条目单独占一行,可使用以下代码生成格式化后的JSON:
import json with open("input.json", "r", encoding="utf-8") as infile: raw_data = json.load(infile) with open("output_formatted.json", "w", encoding="utf-8") as outfile: # 写入外层结构开头 outfile.write('{"responses":[\n') # 遍历条目并写入,处理末尾逗号 entries = raw_data["responses"] for i, entry in enumerate(entries): json.dump(entry, outfile) if i != len(entries) - 1: outfile.write(",\n") else: outfile.write("\n") # 写入外层结构结尾 outfile.write("]}")
此方案生成的文件可直接用pd.read_json读取,无需额外参数。
内容的提问来源于stack exchange,提问作者AldanaBRZ
相关产品推荐
相关产品推荐

