DEV Community

Cover image for Python Convert JSON to SQLite
Kamran Ahmed Khan
Kamran Ahmed Khan

Posted on

33

Python Convert JSON to SQLite

Here are the detailed steps to convert JSON to SQLite using Python:

Install the required libraries:

pip install sqlite3
pip install json
Enter fullscreen mode Exit fullscreen mode

Import the required libraries:

import sqlite3
import json
Enter fullscreen mode Exit fullscreen mode

Open a connection to the SQLite database:

conn = sqlite3.connect('example.db')
Enter fullscreen mode Exit fullscreen mode

Open the JSON file:

with open('example.json', 'r') as json_file:
    data = json.load(json_file)
Enter fullscreen mode Exit fullscreen mode

Iterate through the JSON data and insert it into the SQLite table:

for item in data:
    conn.execute("INSERT INTO example_table (field1, field2, field3) VALUES (?, ?, ?)", 
                 (item["field1"], item["field2"], item["field3"]))
Enter fullscreen mode Exit fullscreen mode

Commit the changes and close the connection:

conn.commit()
conn.close()
Enter fullscreen mode Exit fullscreen mode

Note:

  • Replace 'example.db' and 'example.json' with the appropriate file name, and 'example_table' with the appropriate table name

  • Also, you may need to create the table before inserting the data, you can check this by using the below command

conn.execute("CREATE TABLE example_table (field1 text, field2 text, field3 text);")
Enter fullscreen mode Exit fullscreen mode

Example:

import sqlite3
import json

conn = sqlite3.connect('example.db')
conn.execute("CREATE TABLE example_table (field1 text, field2 text, field3 text);")
with open('example.json', 'r') as json_file:
    data = json.load(json_file)
    for item in data:
        conn.execute("INSERT INTO example_table (field1, field2, field3) VALUES (?, ?, ?)", (item["field1"], item["field2"], item["field3"]))
conn.commit()
conn.close()
Enter fullscreen mode Exit fullscreen mode

This will create a SQLite database file named 'example.db' in the current directory and insert the data from 'example.json' into a table named 'example_table'.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay