0

I am new to python and as per my thesis work I am trying to convert JSON to csv.I am able to download data in JSON but when I am writing it back using dictionaries it is not converting JSON to CSV with every column.

    import pandas as pd
    import statsmodels.formula.api as smf
    import statsmodels.api as sm
    import matplotlib.pyplot as plt
    import numpy as np
    import requests
    from pprint import pprint
    import csv
    from time import sleep

    s1='https://fantasy.premierleague.com/drf/element-summary/'
    print s1

    players = []
    for player_link in range(1,450,1):
        link = s1+""+str(player_link)
        print link
        r = requests.get(link)
        print r
        player =r.json() 
        players.append(player)
        sleep(1)



with open('C:\Users\dell\Downloads\players_new2.csv', 'w') as f:  # Just use 'w' mode in 3.x
     w = csv.DictWriter(f,player.keys())
     w.writeheader()
     for player in players:        
         w.writerow(player)

I have uploaded the expected output(dec_15_expected.csv) and the program out with file name "player_new_wrong_output.csv"

https://drive.google.com/drive/folders/0BwKYmRU_0K6tZUljd3Q0aG1LT0U?usp=sharing

It will be a great help if some can tell what I am doing wrong.

1 Answers1

1

Converting JSON to CSV is simple with pandas. Try this:

import pandas as pd

df=pd.read_json("input.json")
df.to_csv('output.csv')
Nikhil Baby
  • 863
  • 3
  • 10
  • 22