再次将JSON转换为CSV

时间:2019-05-08 13:41:25

标签: python json csv

我正在经历一场噩梦,试图将JSON转换为CSV,我试图遵循此处的其他主题,但是我绝对是新手,如果有人可以指点我,我为此付出了很多努力朝着正确的方向前进,我将非常感激。

我将在下面包含JSON示例,对于重复多次提出的问题深感抱歉。

{
"ApiMessage": "Inventory Returned",
"ApiNumber": "InvS001",
"inventoryResponse": [
    {
        "Sku_Id": "007BLKWHT3",
        "Total_Stock": 0,
        "Unavailable": 0
    },
    {
        "Sku_Id": "007BLKWHT4",
        "Total_Stock": 2,
        "Unavailable": 1
    },
    {
        "Sku_Id": "007BLKWHT5",
        "Total_Stock": 0,
        "Unavailable": 0
    },

我只想要它,所以我可以创建一个包含三列的CSV文件,每一列中的值

所以..

Sku ID         Total_Stock          Unavailable
dsdsdsdsd           2                    0

3 个答案:

答案 0 :(得分:3)

使用csv.DictWriter将词典列表写入文件

import csv

dct = {
"ApiMessage": "Inventory Returned",
"ApiNumber": "InvS001",
"inventoryResponse": [
    {
        "Sku_Id": "007BLKWHT3",
        "Total_Stock": 0,
        "Unavailable": 0
    },
    {
        "Sku_Id": "007BLKWHT4",
        "Total_Stock": 2,
        "Unavailable": 1
    },
    {
        "Sku_Id": "007BLKWHT5",
        "Total_Stock": 0,
        "Unavailable": 0
    }] }

#Open csv file
with open('file.txt', 'w') as fp:
    #Open dict writer with fieldnames
    writer = csv.DictWriter(fp, fieldnames=['Sku_Id', 'Total_Stock', 'Unavailable'], delimiter=',')
    #Write header and write all rows
    writer.writeheader()
    print(writer.writerows(dct['inventoryResponse']))

输出将为

Sku_Id,Total_Stock,Unavailable
007BLKWHT3,0,0
007BLKWHT4,2,1
007BLKWHT5,0,0

答案 1 :(得分:0)

使用熊猫读取json,然后导出为CSV。

下面是在一行中执行此操作的示例:

https://copdips.com/2018/06/converting-python-json-list-to-csv-in-2-lines-of-code-by-pandas.html

答案 2 :(得分:0)

我手头写了这个解决方案,所以它不是最好的(您可以使用csvpandas或为此提供的许多库之一,看起来可以做得更好,但是如果您只需要它我相信一次就能做到这一点:

myjson = {
    "ApiMessage": "Inventory Returned",
    "ApiNumber": "InvS001",
    "inventoryResponse": [
        {
            "Sku_Id": "007BLKWHT3",
            "Total_Stock": 0,
            "Unavailable": 0
        },
        {
            "Sku_Id": "007BLKWHT4",
            "Total_Stock": 2,
            "Unavailable": 1
        },
        {
            "Sku_Id": "007BLKWHT5",
            "Total_Stock": 0,
            "Unavailable": 0
        }
    ]
}

DELIMITER = "         "

with open("my_file.csv", "w") as csvfile:
    csvfile.write(DELIMITER.join(["Sku ID", "Total_Stock", "Unavailable"]) + "\n")
    for item in myjson["inventoryResponse"]:
        csvfile.write(DELIMITER.join([str(e) for e in item.values()]) + "\n")