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 , 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) entry in json_input:     print(entry) 

your assignment of sys.stdout = filename not idiomatic, many people may not understand doing. key misunderstanding appear have python interpret either fact have imported csv or extension of file have opened , automatically write valid lines file given list of dictionaries (which .json gets parsed as).

i present full example of how write dictionary-like data contrived json reproducability:

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

first, using standard library:

import json import csv  data = json.loads(jsonstr)  open('outputfile3.csv', 'w') f:     writer = csv.dictwriter(f, fieldnames=['field1', 'field2'])     writer.writeheader()     writer.writerows(data) 

then more succinctly using pandas:

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

Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -