如何使用python

时间:2016-07-08 13:17:41

标签: python json csv

我有以下JSON:

"item": [
            {
                "id": "3",
                "num": 0,
                "name": "de",
                "leve": {
                    "label": [
                        "Ini",
                        "Sec",
                        "Coo"
                    ],
                    "effect": [
                        "{{ e5 }} -> {{ e5NL }}",
                        "{{ e1 }} -> {{ e1NL }}",
                        "{{ cooldown }} -> {{ cooldownnNL }}"
                    ]
                },
            },
            {
                "id": "4",
                "num": 0,
                "name": "de",
                "leveltip": {
                    "label": [
                        "Initial Damage",
                        "Secondary Damage",
                        "Cooldown"
                    ],
                    "effect": [
                        "{{ e5 }} -> {{ e5NL }}",
                        "{{ e1 }} -> {{ e1NL }}",
                        "{{ cooldown }} -> {{ cooldownnNL }}"
                    ]
                },
            },
            {
                "id": "5",
                "num": 0,
                "name": "de",
                "leveltip": {
                    "label": [
                        "Initial Damage",
                        "Secondary Damage",
                        "Cooldown"
                    ],
                    "effect": [
                        "{{ e5 }} -> {{ e5NL }}",
                        "{{ e1 }} -> {{ e1NL }}",
                        "{{ coo}} -> {{ cooNL }}"
                    ]
                },
            },
        ],

我想将其保存到csv文件中,该文件包含所有数据到如下所示的单独表格中:

item_id item_name item_num item_level_label_inti item_level_effect_inti

 3        de        0       ini                   {{ e5 }} -> {{ e5NL }}
 4        de        0       ini                   {{ e5 }} -> {{ e5NL }}

与上面的列一样,它将所有数据包含在一列

2 个答案:

答案 0 :(得分:0)

有关同一问题,请参阅this post

由于嵌套的json对象,您将遇到转换问题,因此您需要先将它们展平,然后将其转换为CSV

答案 1 :(得分:0)

以下是实施方案,但在您的输入中id 3有一个leve的不同密钥leveltip。所以我认为这是一个错误的条目。

import csv
file_name = 'out.csv'
data = [(item['id'],item['name'],item['num'],item['leveltip']['label'][0],item['leveltip']['effect'][0]) for item in maindict['item']]
with open(file_name, "wb") as csv_file:
    writer = csv.writer(csv_file, delimiter=',')
    writer.writerow(["item_id","item_name","item_num","item_level_label_inti","item_level_effect_inti"])
        for line in data:
            writer.writerow(line)

<强>工作

创建一个元组列表,这些元组以所需格式收集所有数据,然后使用csv file包写在csv上。