You can use a loop to iterate through the JSON data and insert each row into the PostgreSQL database. Here's an example of how you can do this in Python using the psycopg2 library:
import psycopg2
import json
# Connect to the PostgreSQL database
conn = psycopg2.connect(
dbname="database_name",
user="username",
password="password",
host="localhost"
)
# Get the JSON data and parse it into a list of dictionaries
json_data = '[{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]'
data = json.loads(json_data)
# Define the SQL statement for inserting a single row
sql = "INSERT INTO table_name (name, age) VALUES (%s, %s)"
# Loop through the list of dictionaries and insert each row into the database
with conn.cursor() as cur:
for row in data:
values = (row["name"], row["age"])
cur.execute(sql, values)
conn.commit()
# Close the database connection
conn.close()
In this example, we first establish a connection to the PostgreSQL database using the psycopg2 library. We then define a JSON string with sample data and parse it into a list of dictionaries using the json.loads() method.
We define an SQL statement for inserting a single row into a table and use a loop to iterate through the list of dictionaries. For each dictionary, we extract the name and age values and insert them into the table using the execute() method of the psycopg2 cursor.
Finally, we commit the changes to the database and close the connection. Note that you'll need to replace "databasename", "username", "password", "host", "tablename" with your own values.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-06-14 16:13:22 +0000
Seen: 13 times
Last updated: Jun 14 '23
What is the method to retrieve the JSON data from a column in SQL?
How to build an SQLAlchemy engine that uses psycopg3 as its foundation?
How can a string column be transformed into an array column in Django PostgreSQL migration?
Can we deploy a Python application with PostgreSQL on Heroku?
What is the process of developing two databases in a Django application using docker-compose?
How can a web application be developed to send distinct emails upon clicking the SUBMIT button?
How can Python import data from a centralized location?
How to analyze SQL using Python?
How can the SQL debug mode be activated in PostgreSQL version 15.2?
What is the procedure for using pg_restore on Windows with Docker?