Sachin Jaiswal
Sachin Jaiswal

Reputation: 151

how to write nested json data to CSV using python

I have data which I fetched from URL and I get a JSON containing the data as nested LIST and DICTIONARY. Now I want to write this data into CSV file.

{
"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
        }
    }
}

How can I iterate through all the nested values and write them in a CSV file? I want the output for all data like this:

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

Upvotes: 2

Views: 3650

Answers (1)

Rohan Khude
Rohan Khude

Reputation: 4883

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"]])

Output

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

Upvotes: 2

Related Questions