0

链接中共享的尝试解决方案 :: 将json 嵌套到 csv - 通用方法

这适用于 Sample 1 ,但只为 Sample 2 提供一行。有没有办法让通用 python 代码同时处理 Sample 1 和 Sample 2。

样品 1 ::

{
    "Response": "Success",
    "Message": "",
    "HasWarning": false,
    "Type": 100,
    "RateLimit": {},
    "Data": {
        "Aggregated": false,
        "TimeFrom": 1234567800,
        "TimeTo": 1234567900,
        "Data": [
            {
                "id": 11,
                "symbol": "AAA",
                "time": 1234567800,
                "block_time": 123.282828282828,
                "block_size": 1212121,
                "current_supply": 10101010
            },
            {
                "id": 12,
                "symbol": "BBB",
                "time": 1234567900,
                "block_time": 234.696969696969,
                "block_size": 1313131,
                "current_supply": 20202020
            },
        ]
    }
}

样本 2::

{
    "Response": "Success",
    "Message": "Summary succesfully returned!",
    "Data": {
        "11": {
            "Id": "3333",
            "Url": "test/11.png",
            "value": "11",
            "Name": "11 entries (11)"
        },
        "122": {
            "Id": "5555555",
            "Url": "test/122.png",
            "Symbol": "122",
            "Name": "122 cases (122)"
        }
     },
    "Limit": {},
    "HasWarning": False,
    "Type": 50
}
4

1 回答 1

0

试试这个,你需要从这里安装 flatten_json

import sys
import csv
import json
from flatten_json import flatten


data = json.load(open(sys.argv[1]))
data = flatten(data)

with open('foo.csv', 'w') as f:
    out = csv.DictWriter(f, data.keys())
    out.writeheader()
    out.writerow(data)

输出

> cat foo.csv
Response,Message,Data_11_Id,Data_11_Url,Data_11_value,Data_11_Name,Data_122_Id,Data_122_Url,Data_122_Symbol,Data_122_Name,Limit,HasWarning,Type
Success,Summary succesfully returned!,3333,test/11.png,11,11 entries (11),5555555,test/122.png,122,122 cases (122),{},False,50

注意:False在Json中不正确,需要改成false

于 2022-03-02T04:19:05.013 回答