Python JSON ->CSV不同的标题

zy1mlcev  于 2022-12-05  发布在  Python
关注(0)|答案(1)|浏览(158)

我有一个json文件,是这样的:

{"16CD7631-0ED0-4DA0-8D3B-8BBB41992EED": {"id": "16CD7631-0ED0-4DA0-8D3B-8BBB41992EED", "longitude": "-122.406417", "reportType": "Other", "latitude": "37.785834"}, "91CA4A9C-9A48-41A2-8453-07CBC8DC723E": {"id": "91CA4A9C-9A48-41A2-8453-07CBC8DC723E", "longitude": "-1.1932383", "reportType": "Street Obstruction", "latitude": "45.8827419"}}

目标是将其转换为csv文件,如下所示:

id,longitude,reportType,latitude
16CD7631-0ED0-4DA0-8D3B-8BBB41992EED,-122.406417,Other,37.785834
91CA4A9C-9A48-41A2-8453-07CBC8DC723E,-1.1932383,Street Obstruction,45.8827419

我试着

with open('sample.json', encoding='utf-8') as inputfile:
        df = pd.read_json(inputfile)

df.to_csv('csvfile.csv', encoding='utf-8', index=False)

但是因为每个文档的名称都是以它的id命名的,所以我得到了不正确的输出。实现我的目标的最好方法是什么?谢谢

n53p2ov0

n53p2ov01#

您可以使用pandas.json_normalize
试试这个:

import json
import pandas as pd

with open('sample.json', encoding='utf-8') as inputfile:
    data = json.load(inputfile)
    df = pd.json_normalize(data[k] for k in data.keys())
#输出:
print(df.to_string())

                                     id    longitude          reportType    latitude
0  16CD7631-0ED0-4DA0-8D3B-8BBB41992EED  -122.406417               Other   37.785834
1  91CA4A9C-9A48-41A2-8453-07CBC8DC723E   -1.1932383  Street Obstruction  45.8827419

相关问题