社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

希望在Python中将JSON文件转换为CSV

Eja • 3 年前 • 1216 次点击  

Nested json to csv - generic approach

这对示例1有效,但对示例2只给出了一行。 有没有办法让通用python代码同时处理示例1和示例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
}
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/132885
 
1216 次点击  
文章 [ 1 ]  |  最新文章 3 年前
krishna
Reply   •   1 楼
krishna    3 年前

试试这个,你需要从 here

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