【问题标题】:Python JSON -> CSV different headersPython JSON -> CSV 不同的标题
【发布时间】:2022-12-05 04:47:01
【问题描述】:

我有一个像这样的 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,所以我得到了不正确的输出。实现我的目标的最佳方法是什么?谢谢

【问题讨论】:

    标签: python json pandas csv


    【解决方案1】:

    您可以使用pandas.json_normalize

    尝试这个 :

    import json
    import pandas as pd
    
    with open('sample.json', encoding='utf-8') as inputfile:
        df = pd.json_normalize(data[k] for k in json.load(inputfile).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
    

    【讨论】:

      猜你喜欢
      • 2022-11-02
      • 2020-03-29
      • 2019-02-14
      • 1970-01-01
      • 1970-01-01
      • 2011-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多