-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvert.py
More file actions
67 lines (54 loc) · 1.4 KB
/
convert.py
File metadata and controls
67 lines (54 loc) · 1.4 KB
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
import sqlite3
import sys
import time
def utf8(val):
if not isinstance(val, basestring):
return str(val)
if not isinstance(val, str):
val = val.encode('utf8')
return val
def outputJSONObject(key, val, last):
if val is None:
val = ''
obj = ''
obj += '\t\t"' + utf8(key) + '" : '
obj += '"' + utf8(val) + '"'
if last != True:
obj+=','
obj+='\n'
return obj
if len(sys.argv) < 2:
print "Error: Need to pass in SQLite database file to convert"
sys.exit()
db = sys.argv[1].encode('utf-8')
con = sqlite3.connect(db)
con.row_factory = sqlite3.Row
cur = con.cursor()
cur.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = [item[0] for item in cur.fetchall()]
startTime = time.time()
for table in tables:
cur = con.cursor()
cur.execute("select * from " + table)
col_names = [cn[0] for cn in cur.description]
with open(table + ".json", "w") as f:
f.write("[\n")
items = cur.fetchall()
for i, item in enumerate(items):
if item == None:
break
json = '\t{\n'
for j, col in enumerate(col_names):
last = j == (len(col_names)-1)
json += outputJSONObject(col, item[col], last)
if i != (len(items)-1):
#if i < 10000:
json += '\t},\n'
else:
json += '\t}\n'
f.write(json)
f.write("]")
cur.close()
endTime = time.time()
totalTime = endTime - startTime
print "SQLite to JSON conversion took {0:.2f} seconds".format(totalTime)