Skip to content

Instantly share code, notes, and snippets.

@vsooda
Created April 17, 2018 09:59
Show Gist options
  • Save vsooda/150500180ca6f183f8316eede8cbfe53 to your computer and use it in GitHub Desktop.
Save vsooda/150500180ca6f183f8316eede8cbfe53 to your computer and use it in GitHub Desktop.
csv2json
default 1 2 5 11 9 2 4 1
4990 3 2 0 1 3 1
5238 3 2 0 4 6 1
4999 3 0 1 1
3387 2 2 5 11 9 2 5 1
5232 1
5018 3 0 3 1
#! /usr/bin/env python2.7
#coding=utf-8
import csv
import json
import io
import os
if __name__ == '__main__':
filenames = '2.csv'
collum_names = ['id' ,'long','high','isLiuhai','liuhaiType','maweiType','pianfen','fajibianyuan','fajidingbu','toufaquzhi']
rows = []
json_data = {}
with open(filenames, 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
for row in spamreader:
rows.append(row)
for row in rows:
row_dict = {}
row_id = row[0]
for i in xrange(1, len(collum_names)):
collum_key = collum_names[i]
row_dict[collum_key] = row[i]
json_data[row_id] = row_dict
base_name = os.path.basename(filenames)
base_name = os.path.splitext(base_name)[0]
output_json_name = base_name + ".json"
a = [{'name':1, 'child' : [{'name': 11, 'child': [{'name': 111, 'child': ['empty']}, {'name':112, 'child': ['empty']}]}, {'name':22, 'child': ['empty']}]}]
print json.dumps(a, indent=4)
#print json.dumps(json_data, indent=4)
with io.open(output_json_name, 'w', encoding='utf-8') as f:
f.write(json.dumps(json_data, indent=4, ensure_ascii=False).decode('utf-8'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment