Created
December 18, 2011 12:32
-
-
Save snim2/1493261 to your computer and use it in GitHub Desktop.
Convert Kasabi JSON to CSV. This parser is designed to parse the results of http://kasabi.com/ SPARQL queries and write them out as CSV files for use with a spreadsheet.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
Convert Kasabi JSON to CSV. | |
This parser is designed to parse the results of http://kasabi.com/ SPARQL | |
queries and write them out as CSV files for use with a spreadsheet. | |
You can see an example SPARQL query here: | |
http://goo.gl/HIQLT | |
and the resulting spreadsheet here: | |
http://goo.gl/Cm2Y5 | |
- (c) Sarah Mount (@snim2), December 2011 | |
""" | |
import json | |
import csv | |
import sys | |
if __name__ == '__main__': | |
if len(sys.argv) < 3: | |
print 'Usage: $ json2csv.py jsonfile csvfile' | |
sys.exit(1) | |
# Read JSON file. | |
with open(sys.argv[1], 'r') as fd_r: | |
data_json = fd_r.read() | |
# Convert JSON data to Python types. | |
data_json = fd_r.read() | |
# Convert JSON data to Python types. | |
decoder = json.JSONDecoder() | |
data_raw = decoder.decode(data_json) | |
# Convert raw data to CSV. | |
data_csv = [] # WRITEME | |
# Column headers. | |
headers = data_raw['head']['vars'] | |
data_csv.append(headers) | |
# Row data. | |
data_rows = data_raw['results']['bindings'] | |
for row in data_rows: | |
r = [(row['name']['value']).encode('utf-8'), | |
(row['postcode']['value']).encode('utf-8'), | |
float(row['lat']['value']), | |
float(row['long']['value'])] | |
data_csv.append(r) | |
# Write CSV file. | |
with open(sys.argv[2], 'w') as fd_w: | |
writer = csv.writer(fd_w) | |
writer.writerows(data_csv) | |
# Exit. | |
sys.exit(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment