Created
July 20, 2014 05:52
-
-
Save hitsujixgit/f4fb6867e0ff23a7020a to your computer and use it in GitHub Desktop.
Read a json file written with specific format, convert the data to 2nd dim list and write it as a csv file.
This file contains hidden or 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
#coding:utf-8 | |
''' | |
Created on 2014/7/20 | |
@author: Tae Matsumoto | |
JSONファイルを読み込み、同名のCSVファイルを出力します。 | |
読み込む対象のJSONファイルの構造は下記の通り。 | |
[{'key':区名1, 'stat':{0:0歳人口,1:1歳人口,...}},{'key':区名2, 'stat':{0:0歳人口,1:1歳人口,...}},...] | |
''' | |
import csv, json | |
filename = 'yokohama_stat' | |
# read json file. | |
json_data = open(filename+'.json') | |
data = json.load(json_data) | |
json_data.close() | |
res = list() | |
# add header | |
tmp = list(data[0]['stat'].items()) + [('key', data[0]['key'])] | |
tmp.sort() | |
header = [x[0] for x in tmp] | |
res.append(header) | |
# add elements | |
for row in data: | |
row_list = list(row['stat'].items()) + [('key', row['key'])] | |
row_list.sort() | |
vals = [x[1] for x in row_list] | |
res.append(vals) | |
# display resulsts | |
print res | |
# write a file as csv | |
with open(filename+'.csv', 'wb') as f: | |
mywriter = csv.writer(f, delimiter = ',') | |
mywriter.writerows(res) | |
f.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment