【问题标题】:Json data to CSV file format using Python [closed]使用 Python 将 Json 数据转换为 CSV 文件格式 [关闭]
【发布时间】:2021-09-11 07:04:58
【问题描述】:

我有想要转换为 CSV 文件的 JSON 数据。如何使用 Python 做到这一点?

下面是json结构。

{
    "data": [
        {
            "matter_id": 1,
            "billing_clientId": 1,
            "billing_contactID": 1,
            "branch_code": "8032FHDSL",
            "category": "sadsaddda",
        }
    ]
}

我在下面尝试过,但它抛出了 ValueError: "Invalid file path or buffer object type: "

for record in serializer.data:
    import pandas as pd
    import json
    df = pd.read_json(record)
    print('df----->', df)
    df.to_csv("/home/satyajitbarik/test.csv", index = None)

【问题讨论】:

    标签: python json django csv django-rest-framework


    【解决方案1】:

    这行得通:

    import json
    
    json_data = {
        "data": [
            {
                "matter_id": 1,
                "billing_clientId": 1,
                "billing_contactID": 1,
                "branch_code": "8032FHDSL",
                "category": "sadsaddda",
            }
        ]
    }
    
    data = json_data['data'][0]
    
    output_file = open('output_file.csv', 'w')
    
    
    #This would be "for key, value in data.iteritems():" in python 2
    for key, value in data.items():
        output_file.write(str(key) + '; ' + str(value) + '\n')
    
    output_file.close()
    

    注意:字典“数据”在 python 3.5 及以下版本中应该是 OrderedDict

    【讨论】:

    • 在这一行,data = json_data['data'][0] 我得到 TypeError: list indices must be integers or slices, not str
    • 这可能是错字吗?它在我的机器上运行良好。我正在使用 Python 3.9.0
    • 当传递静态数据为json_data时,这也适用于我的机器,当我制作动态json_data=serializer.data时,它会抛出这个错误。
    • 整个代码在这个链接里---> pastebin.com/bPhEKt07
    • 我相信这意味着 JSON 文件“serializer.data”的格式与示例数据不同。获得 JSON 文件后,尝试将其打印到控制台,然后相应地格式化这一行
    【解决方案2】:

    首先,导入应该在 for 循环之外而不是内部进行。将导入放在函数中会导致对该函数的调用花费更长的时间。

    import json
    import csv
    
    json_data = {
        "data": [
            {
                "matter_id": 1,
                "billing_clientId": 1,
                "billing_contactID": 1,
                "branch_code": "8032FHDSL",
                "category": "sadsaddda",
            }
        ]
    }
    
    # with open('data.json') as json_file:
    #     data = json.load(json_data)
    
    some_data = json_data['data']
    
    data_file = open('data_file.csv', 'w')
    
    csv_writer = csv.writer(data_file)
    count = 0
     
    for row in some_data:
        if count == 0:
     
            # Writing headers of CSV file
            header = row.keys()
            csv_writer.writerow(header)
            count += 1
     
        # Writing data of CSV file
        csv_writer.writerow(row.values())
     
    data_file.close()
    

    【讨论】:

    • 虽然导入确实应该移到顶部,但原因并不是“对于每次迭代,您的代码都会再次导入包,这可能会影响您的记忆。”
    • 感谢指正。 @juanpa.arrivillaga 现在是有效的原因吗?
    猜你喜欢
    • 2020-11-11
    • 1970-01-01
    • 2022-06-10
    • 2018-03-06
    • 2019-08-15
    • 2011-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多