Tuesday, May 5, 2015

Converting JSON to CSV

Python is very versatile at converting JSON to CSV.

For the absolute beginners, here's what a JSON file looks like. Let's call this file countries.json.

{ "countries":[
    {
         "country": "United States",
         "capital": "Washington DC",
         "latitude": 38,
         "currency": "US Dollar"
    }
    {
         "country": "United Kingdom",
         "capital": "London",
         "latitude": 51,
         "currency": "Pound"
    }
]}

Here's a guide at converting JSON to CSV.

import json
import csv
data = open('countries.json')
x = json.load(data)
data.close()

file=csv.writer(open('test.csv','wb+'))

for y in x:
    file.writerow([y['country'], y['capital']], y['latitude'], y['currency'])
In the first two lines, you import the json and csv packages. Be sure to install them if you haven't already. The third line allows Python to open the file. But it still needs to be properly processed, and that's the purpose of the fourth and fifth lines. Thereafter, it's time to start the CSV transcription process. Calling "csv.writer" and setting the second parameter to 'wb+' ensures that you can write in binary mode. (w refers to write and b refers to binary mode. Finally, the + ensures that it can read as well.) The last two lines start the actual CSV writing process. "for y in x" is something like telling Python "for every observation in the dataset". Since y refers to an individual observation, the last line tells Python to write the country, capital, latitude, and currency into the file. These four properties will of course be separated by commas.

Sunday, March 29, 2015

ipython notebook

The IPython Notebook is a web-based interactive computational environment. Among the various Python environments I've tried so far, IPython stands out for its ease of use.

Friday, March 27, 2015

Hello!

I am an aspiring Python master. In subsequent posts I will document my learning of Python.