Skip to content

Instantly share code, notes, and snippets.

@CJHwong
Last active February 5, 2017 22:03
Show Gist options
  • Save CJHwong/193c0f6f7134ee7d44fb8d020939b596 to your computer and use it in GitHub Desktop.
Save CJHwong/193c0f6f7134ee7d44fb8d020939b596 to your computer and use it in GitHub Desktop.
Convert data in SQLite to JSON
import sqlite3
import json
def dump_from_sqlite():
conn = sqlite3.connect('db.sqlite')
c = conn.cursor()
c.execute("SELECT name FROM sqlite_master WHERE type='table';")
for t in c.fetchall():
c.execute("SELECT * FROM " + t[0])
cols = []
for name in c.description:
cols.append(name[0])
output = []
for row in c.fetchall():
data = {}
for i in range(len(cols)):
data[cols[i]] = row[i]
output.append(data)
with open(t[0] + '.json', 'w') as f:
f.write(json.dumps(output, sort_keys=True, indent=4))
conn.close()
if __name__ == '__main__':
# Convert data in SQLite to JSON
dump_from_sqlite()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment