Donald Woolfolk
Donald Woolfolk

Reputation: 11

json is not converting to csv in python 3.5

#!/usr/bin/env python

import requests
import csv
import json
import sys

s = requests.Session()

r = s.get('https://onevideo.aol.com/sessions/login?un=username&pw=password')

r.status_code

if r.status_code == 200:
    print("Logged in successfully")

else:
    print("Check username and password")

filename  = open('outputfile3.csv', 'w')
sys.stdout = filename
data = s.get('https://onevideo.aol.com/reporting/run_existing_report?report_id=102636').json()
json_input = json.load(data)
for entry in json_input:
    print(entry)

Upvotes: 0

Views: 136

Answers (1)

chthonicdaemon
chthonicdaemon

Reputation: 19760

Your assignment of sys.stdout = filename is not idiomatic, so many people may not even understand exactly what you are doing. The key misunderstanding you appear to have is that Python will interpret either the fact that you have imported csv or the extension of the file you have opened and automatically write valid lines to the file given a list of dictionaries (which is what the .json gets parsed as).

I will present a full example of how to write dictionary-like data with some contrived json for reproducability:

jsonstr = """
    [{"field1": "property11", "field2": "property12"},
     {"field1": "property21", "field2": "property22"},
     {"field1": "property31", "field2": "property32"}]
    """

First, using only the standard library:

import json
import csv

data = json.loads(jsonstr)

with open('outputfile3.csv', 'w') as f:
    writer = csv.DictWriter(f, fieldnames=['field1', 'field2'])
    writer.writeheader()
    writer.writerows(data)

Then much more succinctly using pandas:

import pandas

pandas.read_json(jsonstr).to_csv('outputfile3.csv', index=False)

Upvotes: 1

Related Questions