0
#!/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)
4
  • The result of your s.get call returns: "Logged in successfully". Commented Feb 29, 2016 at 3:02
  • 2
    Please don't assume that people at Stack Overflow know black magic, and can know your problem without you describing it. Commented Feb 29, 2016 at 3:03
  • Use json.loads instead of json.load. I'm not sure if this is the only issue. Commented Feb 29, 2016 at 3:04
  • Shadowfax you are right. I guess my issue as a new user of python is that when I open the outputfile3.csv file the delimiters are not working. Thanks for your response. Commented Feb 29, 2016 at 4:13

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.