Using requests module to export csv
Question: I'm a beginner to Python and I have been trying to export my data to a csv
file but I can't figure out how to get rid of all the brackets and my comma
separated. Ideally I need two columns: one with all values for "count" and one
with values for "month".

Any advice appreciated.

My code:

    
    
    from sunlight import capitolwords
    import requests
    import csv
    
    r = requests.get ('http://capitolwords.org/api/1/dates.json?phrase=guns&start_date=2011-  
    12-01&end_date=2013-01-
    15&granularity=month&sort=count&apikey=ab02633fb17841d09f4c3660e0384ae5')
    data = r.text
    
    ifile = open('guns.csv', 'rb')
    reader = csv.reader(data.splitlines(), delimiter=',')
    for row in reader:
        print row
    

Result:

    
    
      ['{']
      ['    "results": [']
      ['        {']
      ['            "count": 62.0', '']
      ['            "month": "201212"']
      ['        }', '']
      ['        {']
      ['            "count": 36.0', '']
      ['            "month": "201207"']
      ['        }', '']
      ['        {']
      ['            "count": 35.0', '']
      ['            "month": "201112"']
      ['        }', '']
      ['        {']
      ['            "count": 27.0', '']
      ['            "month": "201202"']
      ['        }', '']
      ['        {']
      ['            "count": 27.0', '']
    


Answer: Since the response is a Json, load the json data with:

    
    
    data = r.json()["results"] # read the json response and keep the results part
    

and then write to the csv file:

    
    
    with open("guns.csv", "wb") as csvfile:
        f = csv.writer(csvfile)
        f.writerow(["Count", "Month"]) # write the headers if you like
        for elem in data:
            f.writerow([elem["count"], elem["month"]])
    

