-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsv2json.py
85 lines (70 loc) · 2.44 KB
/
csv2json.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# csv2json.py
#
# Copyright 2009 Brian Gershon -- briang at webcollective.coop
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import getopt
import csv
from os.path import dirname
import simplejson
try:
script, input_file_name, model_name = sys.argv
except ValueError:
print("\nRun via:\n\n%s input_file_name model_name" % sys.argv[0])
print("\ne.g. %s airport.csv app_airport.Airport" % sys.argv[0])
print("\nNote: input_file_name should be a path relative to where this script is.")
sys.exit()
in_file = dirname(__file__) + input_file_name
out_file = dirname(__file__) + input_file_name + ".json"
print("Converting %s from CSV to JSON as %s" % (in_file, out_file))
f = open(in_file, 'r' )
fo = open(out_file, 'w')
reader = csv.reader( f )
header_row = []
entries = []
# debugging
# if model_name == 'app_airport.Airport':
# import pdb ; pdb.set_trace( )
for row in reader:
if not header_row:
header_row = row
continue
pk = row[0]
model = model_name
fields = {}
for i in range(len(row)-1):
active_field = row[i+1]
# convert numeric strings into actual numbers by converting to either int or float
if active_field.isdigit():
try:
new_number = int(active_field)
except ValueError:
new_number = float(active_field)
fields[header_row[i+1]] = new_number
elif active_field.lower() == 'true':
fields[header_row[i+1]] = True
elif active_field.lower() == 'false':
fields[header_row[i+1]] = False
elif active_field.lower() == '':
fields[header_row[i+1]] = None
else:
fields[header_row[i+1]] = active_field.strip()
row_dict = {}
row_dict["pk"] = int(pk)
row_dict["model"] = model_name
row_dict["fields"] = fields
entries.append(row_dict)
fo.write("%s" % simplejson.dumps(entries, indent=4))
f.close()
fo.close()