使用Pandas将嵌套的JSON转换为CSV,然后将CSV转换回JSON

2024-09-28 22:23:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个JSON主体,需要转换为CSV。然后,我需要从CSV进行完美的转换,以输出相同的JSON。因此,首先是JSON到CSV,然后是CSV到JSON

以下是JSON:

{
    "quoteId": "",
    "carrier": "",
    "productType": "",
    "effectiveDate": "",
    "referenceId": "",
    "agencyLocationCode": null,
    "locationId": null,
    "property": {
        "id": "",
        "address": {
            "propertyStreetNumber": "",
            "propertyStreetName": "",
            "propertyAddressLine2": null,
            "propertyCity": "",
            "propertyState": "",
            "propertyZipCode": ""
        },
        "details": null
    }
}

我运行以下代码得到的输出是:

输出csv: enter image description here

代码:

with open('resources/json/file.json') as data_file:    
data = json.load(data_file)
df = pd.json_normalize(data)
df.to_csv("file.csv", index=False, encoding="utf-8")

现在,我希望将CSV转换回完全相同的JSON,目前我运行以下代码:

df = pd.read_csv('file.csv')
df.to_json('new.json')

我得到的输出JSON如下所示:

{
    "quoteId": {
        "0": null
    },
    "carrier": {
        "0": ""
    },
    "productType": {
        "0": ""
    },
    "effectiveDate": {
        "0": ""
    },
    "referenceId": {
        "0": 62646354
    },
    "agencyLocationCode": {
        "0": null
    },
    "locationId": {
        "0": null
    },
    "losses": {
        "0": null
    },
    "property.id": {
        "0": null
    },
    "property.address.propertyStreetNumber": {
        "0": ""
    },
    "property.address.propertyStreetName": {
        "0": ""
    },
    "property.address.propertyAddressLine2": {
        "0": null
    },
    "property.address.propertyCity": {
        "0": ""
    },
    "property.address.propertyState": {
        "0": ""
    },
    "property.address.propertyZipCode": {
        "0": ""
    },
    "property.details": ""
}

我需要输出json看起来像第一个。请帮忙


Tags: csv代码jsondfdataaddresspropertynull