使用Pandas在Python中加载并将JSON转换为Excel

1 投票
1 回答
38 浏览
提问于 2025-04-14 16:12

我有一些文本文件,里面包含了JSON格式的数据。现在我想用Python通过Pandas把这些JSON转换成Excel文件。

这是我文件中的JSON格式(json_test.txt)

{"time_utc":"2024-01-01T22:07:48.435Z","First Name":"Joe","Last Name":"Smith","Dept":"HR"}
{"time_utc":"2024-01-01T22:07:48.435Z","First Name":"Sarah","Last Name":"Smith","Dept":"HR"}
{"time_utc":"2024-01-01T22:07:48.435Z","First Name":"Mary","Last Name":"Smith","Dept":"Finance"}
{"time_utc":"2024-01-01T22:07:48.435Z","First Name":"James","Last Name":"Smith","Dept":"Marketing"}
{"time_utc":"2024-01-01T22:07:48.435Z","First Name":"Sarah","Last Name":"Smith","Dept":"Marketing"}

我不太确定最有效的做法是什么。我最开始写的代码是

import os
import pathlib as Path
import json
import pandas as pd

df_json = pd.DataFrame()

def main():

    with open("json_test.txt", 'r') as f:
        data_str = f.readlines()
        df_json = json.load(data_str)
        f.close()

        df_json.to_excel('json_to_excel.xlsx', index=False)


if __name__ == '__main__':
    main()

当我运行这段代码时,出现了一个错误:“TypeError(f'the JSON object must be str, bytes or bytearray,”这个错误出现在json.loads()这一行。

1 个回答

3

看起来你的文件里有JSON行格式的数据。你可以在使用 pd.read_json 的时候加上 lines=True 这个参数:

df = pd.read_json("data.json", lines=True)
df.to_excel("data.xlsx", index=False)

这样就会生成一个叫 data.xlsx 的文件(下面是用LibreOffice打开的截图):

enter image description here

撰写回答