Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.