Ultraviolet
Ultraviolet

Reputation: 13

Python Program to convert complicated json into csv for a complete beginner

I understand the very basics of programming in python and here is my problem. I have following json file from the developer API for League of Legends (a video game) (excerpt):

 "keys": {
          "35": "Shaco",
          "36": "DrMundo",
          "33": "Rammus",
          AND SO ON..
       },
       "data": {
           "Aatrox": {
               "tags": [
                   "Fighter",
                   "Tank"
               ],
                "stats": {
                    "attackrange": 150,
                    "mpperlevel": 45,
                    "mp": 105.6,
                    "attackdamage": 60.376,
                    AND SO ON...

             },
             AND SO ON.

My code:

#import dependencies
#to understand json
import json

#to write csv file
import csv

#to output json in a readable way in the command line
from pprint import pprint

#create the output file
outfile_path='output.csv'

#open up the file and tell the programm to write in it
writer = csv.writer(open(outfile_path, 'w'))


#Create custom headers for the data
headers =['armor', 'armorperlevel', 'attackdamage','attackdamageperlevel','attackrange', 'attackspeedoffset', 'attackspeedperlevel', 'crit', 'critperlevel', 'hp', 'hpperlevel', 'hpregen', 'hpregenperlevel', 'movespeed', 'mp', 'mpperlevel', 'mpregen', 'mpregenperlevel', 'spellblock', 'spellblockperlevel']
writer.writerow(headers)

#open data file, in order to manipulate it
with open('data.json') as data_file:
    data = json.load(data_file)

#print stats for the keys Aatrox
aatrox = data['data']['Aatrox']['stats']
pprint(aatrox)

What I have done so far:

What I would like to do now:

I believe that I will be able to create a loop that goes through all the keys by myself. However I fail to find easy to understand information on how to write the dictionary to a CSV-file in my desired format. Could anyone help me out with this. What I am most interested in understanding is:

Upvotes: 1

Views: 163

Answers (1)

unutbu
unutbu

Reputation: 880717

You could use a csv.DictWriter:

import csv

stats =  {
    "attackrange": 150,
    "mpperlevel": 45,
    "mp": 105.6,
    "attackdamage": 60.376,}

headers =['attackdamage','attackrange', 'mp', 'mpperlevel']

with open('output.csv', 'wb') as f:
    writer = csv.DictWriter(
        f, headers, delimiter=',', lineterminator='\n', )
    writer.writeheader()
    writer.writerow(stats)

produces output.csv:

attackdamage,attackrange,mp,mpperlevel
60.376,150,105.6,45

Upvotes: 1

Related Questions