-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexportJSON.py
executable file
·60 lines (47 loc) · 1.46 KB
/
exportJSON.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
#!/usr/bin/env python2.7
#############################################################################
# Purpose:
# Export the Postgres database "lqfb" as JSON format.
#
# Usage:
# exportJSON.py
#
# Files:
# Expects the Python module "psycopg2". Under Mac OS, use "port install
# py27-psycopg2".
#
# Author:
# Niels Lohmann <[email protected]>
#############################################################################
import psycopg2
import json
import datetime
# helper to JSONify datetime in ISO format
dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime.datetime) else None
# connect to database
conn = psycopg2.connect(database="lqfb")
cur = conn.cursor()
# collect list of tables
cur.execute("""SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'""")
tables = list()
for t in cur.fetchall():
tables.append(t[0])
cur.close()
fulldump = dict()
# traverse tables
for table in tables:
query = 'SELECT * FROM ' + table + ';'
cur = conn.cursor()
cur.execute(query)
colnames = [desc[0] for desc in cur.description]
entry = list()
for record in cur:
row = dict()
for i in range(0, len(colnames)):
row[cur.description[i][0]] = record[i]
entry.append(row)
fulldump[table] = {"count": len(entry), "entries": entry}
# output tables as JSON
print(json.dumps(fulldump, default=dthandler, sort_keys=True, indent=2))
# disconnect from database
conn.close()