Skip to content

Instantly share code, notes, and snippets.

@hitsujixgit
Created July 20, 2014 05:52
Show Gist options
  • Save hitsujixgit/f4fb6867e0ff23a7020a to your computer and use it in GitHub Desktop.
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.
#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