Skip to content

Instantly share code, notes, and snippets.

@noureddin
Created January 19, 2021 00:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noureddin/8dd137a8ea784fef40745cc919f6e4a5 to your computer and use it in GitHub Desktop.
Save noureddin/8dd137a8ea784fef40745cc919f6e4a5 to your computer and use it in GitHub Desktop.
Convert SQLite3 table to JSON (using Python3)
#!/usr/bin/env python3
# I assume that the sqlite3 db file given contains one table,
# and that table has the same name as the file (w/o the extension),
# and that you only want that table.
# This is my use-case anyway; feel free to change it to suit your situation.
# License: CC0 (Public Domain)
import sqlite3
import json
import sys
import os
def die(msg):
print(msg, file=sys.stderr)
sys.exit(1)
if len(sys.argv) != 3: die(f'USAGE: {sys.argv[0]} input-file output-file') # if not 2 args; yes, 2 not 3
_, infile, outfile = sys.argv
if not os.path.isfile(infile): die(f"'{infile}' doesn't exist or is not a file")
if os.path.exists(outfile): die(f"'{outfile}' exists; please remove it and try again")
tblname = os.path.basename(infile).split('.')[0]
assert tblname.find('"') == -1
c = sqlite3.connect(infile).cursor()
cols = [ row[1] for row in c.execute(f'pragma table_info("{tblname}")') ]
content = [ dict(zip(cols, row)) for row in c.execute(f'select * from "{tblname}"') ]
with open(outfile, 'w') as f:
json.dump(content, f, ensure_ascii=False, indent=4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment