Sling Academy
Home/SQLite/How to convert SQLIte database to JSON (with Python)

How to convert SQLIte database to JSON (with Python)

Last updated: December 07, 2024

Working with data comes with the frequent need to convert it between different formats. One common scenario is the conversion of a SQLite database to a JSON format. JSON (JavaScript Object Notation) is widely used for data interchange between client and server applications because of its lightweight and readable structure. In this article, we will walk through the process of exporting data from a SQLite database to a JSON format.

Prerequisites

Before we start, make sure you have the following:

  • Python installed on your machine. You can download it from Python's official website.
  • SQLite3 installed on your machine.
  • A sample SQLite database that you want to convert.

Step-by-Step Guide

Step 1: Set up Your Environment

We'll use Python and its built-in modules: sqlite3 for interacting with the SQLite database and json for exporting data to JSON. Let's start by setting up a working environment.

# Assuming you have Python installed.
# Open a terminal and create a new Python file.
# For example: sqlite_to_json.py

import sqlite3
import json

# Path to your SQLite database
db_path = 'example.db'

Step 2: Connect to the SQLite Database

Using the sqlite3 module, connect to the SQLite database.

# Connect to SQLite database
connection = sqlite3.connect(db_path)

# Create a cursor object
cursor = connection.cursor()

Step 3: Read Data from Tables

Next, we need to read data from the tables we want to convert to JSON. Here's an example of how to fetch data from a specific table:

# Assuming you have a table named 'users'
# Fetch all rows from the 'users' table
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()

# Fetch the column names
columns = [column[0] for column in cursor.description]

Step 4: Convert the Data to JSON

Once you have the data from the database, the next step is to convert it into JSON. We'll create a dictionary with the column names as keys and the row data as values.

# Convert sqlite3 row objects to dictionaries
data = []
for row in rows:
    row_dict = {columns[i]: row[i] for i in range(len(columns))}
    data.append(row_dict)

# Convert the list of dictionaries to a JSON string
json_data = json.dumps(data, indent=4)
print(json_data)

Step 5: Save JSON to a File

If you would like to save the JSON data to a file for further use, you can do so using the following code:

# Define the JSON file path
json_file_path = 'output.json'

# Write the JSON data to a file
with open(json_file_path, 'w') as json_file:
    json_file.write(json_data)

Conclusion

Converting a SQLite database to JSON in Python is a straightforward task with the use of the sqlite3 and json modules. This export can facilitate data transfer between different tech stacks and is essential in web development processes. By following the steps above, you can reliably transform your relational database data into a lightweight and efficient JSON format suitable for various applications.

Using Python’s flexibility, the process can be easily adjusted to meet more specific requirements, like handling different data types, formulating more complex SQL queries, or formatting the output JSON in various styles. You'll often find the Bible of data format conversion handy in the toolbox of modern developers.

Next Article: How to rename/ drop an SQLIte database

Previous Article: How to export SQLite database to CSV

Series: Managing databases and tables in SQLite

SQLite

You May Also Like

  • How to use regular expressions (regex) in SQLite
  • SQLite UPSERT tutorial (insert if not exist, update if exist)
  • What is the max size allowed for an SQLite database?
  • SQLite Error: Invalid Value for PRAGMA Configuration
  • SQLite Error: Failed to Load Extension Module
  • SQLite Error: Data Type Mismatch in INSERT Statement
  • SQLite Warning: Query Execution Took Longer Than Expected
  • SQLite Error: Cannot Execute VACUUM on Corrupted Database
  • SQLite Error: Missing Required Index for Query Execution
  • SQLite Error: FTS5 Extension Malfunction Detected
  • SQLite Error: R-Tree Node Size Exceeds Limit
  • SQLite Error: Session Extension: Invalid Changeset Detected
  • SQLite Error: Invalid Use of EXPLAIN Statement
  • SQLite Warning: Database Connection Not Closed Properly
  • SQLite Error: Cannot Attach a Database in Encrypted Mode
  • SQLite Error: Insufficient Privileges for Operation
  • SQLite Error: Cannot Bind Value to Parameter
  • SQLite Error: Maximum String or Blob Size Exceeded
  • SQLite Error: Circular Reference in Foreign Key Constraints