【问题标题】:how to write nested json data to CSV using python如何使用python将嵌套的json数据写入CSV
【发布时间】:2016-07-05 07:40:02
【问题描述】:

我有从 URL 获取的数据,并且我得到一个 JSON,其中包含作为嵌套 LIST 和 DICTIONARY 的数据。现在我想将这些数据写入 CSV 文件。

{
"type": "abs",
"format": "cdg",
"version": "6",
"data": {
    "fff": {
        "version": "6",
        "id": "fff",
        "key": "266",
        "name": "fff",
        "title": "the Darkin Blade"
        "info": {
            "attack": 8,
            "defense": 4,
            "magic": 3,
            "difficulty": 4
        },

        "tags": [
            "Fighter",
            "Tank"
        ],

        "partype": "BloodWell",

        "stats": {
            "hp": 537.8,
            "hpperlevel": 85,
            "mp": 105.6
        }
    },
    "ggg": {
        "version": "6",
        "id": "ggg",
        "key": "103",
        "name": "ggg"
        "info": {
            "attack": 3,
            "defense": 4,
            "magic": 8,
            "difficulty": 5
        },
        "tags": [
            "Mage",
            "Assassin"
        ],
        "partype": "MP",
        "stats": {
            "hp": 514.4,
            "hpperlevel": 80,
            "mp": 334
        }
    }
}

如何遍历所有嵌套值并将它们写入 CSV 文件? 我想要这样的所有数据的输出:

type format version data__ data__|__version data__|__id info_attack
abs  cdg     6       fff     6.13.1          fff         8
abs  cdg     6       ggg     6.13.1          ggg         3

【问题讨论】:

  • 你的问题写得有点模糊 - 也许你可以尝试添加一个你想要得到的输出的例子,以及你到目前为止写的代码。
  • data__ 列之间有什么区别?因为你不能有两个同名的列。
  • data__|__version - 6.13.1 是怎么来的?
  • 是fff中版本的栏目

标签: python json csv


【解决方案1】:
import csv
import json

json_file='sample.json'
with open(json_file, 'r') as json_data:
    x = json.load(json_data)

f = csv.writer(open("test.csv", "w"))

f.writerow(["type", "format", "version", "data__","data__|__version","data__|__id","info_attack","info_defense"])
types=x["type"]
format=x["format"]
root_version=x["version"]
for key in x["data"]:
    f.writerow([types, 
                format, 
                root_version, 
                x["data"][key]["name"],
                x["data"][key]["version"],
                x["data"][key]["id"],
                x["data"][key]["info"]["attack"],
                x["data"][key]["info"]["defense"]])

输出

type,format,version,data__,data__|__id
abs,cdg,6,fff,fff
abs,cdg,6,ggg,ggg

【讨论】:

  • 它看起来很酷,但我如何按照上述格式编写“信息”数据
  • 告诉我“info”的输出结构
  • 只要在上面的数据data__|__info__attack data__|__info__defense中添加这样的列
  • 我增加了攻防栏。如果回答满意,请采纳。谢谢
  • 是否有任何其他方法可以自动执行此操作,而无需将单独的键写为 f.writerow(),因为我的 JSON 数据中包含如此多的字典和列表。
猜你喜欢
  • 2013-10-20
  • 1970-01-01
  • 2018-08-10
  • 2015-06-06
  • 1970-01-01
  • 2022-10-15
  • 2020-12-25
  • 1970-01-01
  • 2013-12-23
相关资源
最近更新 更多