Skip to content

Instantly share code, notes, and snippets.

@seanmckaybeck
Created December 8, 2020 22:05
Show Gist options
  • Save seanmckaybeck/f464ad2e274d14681bd2c2d1acdc1508 to your computer and use it in GitHub Desktop.
Save seanmckaybeck/f464ad2e274d14681bd2c2d1acdc1508 to your computer and use it in GitHub Desktop.
Converts a sqlite database table to a JSON file
import json
import os
import sqlite3
import sys
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
if len(sys.argv) != 4:
print("usage:\n\tsqlite_to_json.py DATABASE TABLE_NAME OUTPUT_FILE")
sys.exit(1)
if not os.path.exists(sys.argv[1]):
print(f"{sys.argv[1]} does not exist")
sys.exit(1)
connection = sqlite3.connect(sys.argv[1])
connection.row_factory = dict_factory
cursor = connection.cursor()
cursor.execute(f"select * from {sys.argv[2]}")
results = cursor.fetchall()
with open(sys.argv[3], 'w') as f:
json.dump(results, f)
connection.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment