Python:将 JsonL 转换为 Json 到 CSV

问题描述

目前正在处理 jsonl 文件,我打算将其转换为 CSV 格式以通过程序运行。但是,我意识到将其从 json 直接转换为 CSV 会更好,因此我在下面编写了一段代码将 json 转换为 csv。但是,在运行此代码之前,我不确定如何将当前的 jsonl 文件转换为所需的 json 格式。如果有人对我有任何解决方案,请告诉我!非常感谢阅读并感谢我能得到的所有帮助。

(仅供参考,我尝试使用下面的 json 到 csv 转换器直接将 jsonl 文件转换,但我在下面收到一条错误消息:)

Converting to CSV: XXX.jsonl
ERROR: Extra data

这是转换代码,希望能帮到你!

from json.decoder import JSONDecodeError
import pandas as pd
import sys
from flatten_json import flatten
import json

def main():
    if len(sys.argv) not in [1,2]:
        sys.exit("Usage: python JsonCon.py [FILENAME.json] \n exitted")

    filename = sys.argv[1]
    print(f"Converting to CSV: {filename}")
    convertFile(filename)

def convertFile(filename):
    try:
        with open(filename) as file:
            jsstring = json.load(file)
            dic_flat = [flatten(d) for d in jsstring]
            df = pd.DataFrame(dic_flat)
            df.to_csv(f'{filename[:-5]}.csv')
    except JSONDecodeError as e:
        print(f'ERROR: {e.msg}')

if __name__ == "__main__":
    main()

解决方法

import json
import csv
import io

# get the JSON objects from JSONL
jsonl_data = """{"a": 1,"b": 123}\n{"a": 2,"b": 234}\n{"a": 3,"b": 345}\n"""
json_lines = tuple(json_line
                   for json_line in jsonl_data.splitlines()
                   if json_line.strip())
jsons_objs = tuple(json.loads(json_line)
                   for json_line in json_lines)

# write them into a CSV file
fake_file = io.StringIO()
writer = csv.writer(fake_file)
writer.writerow(["a","b"])
writer.writerows((value for key,value in sorted(json_obj.items()))
                 for json_obj in jsons_objs)
print(fake_file.getvalue())