The Wayback Machine - https://web.archive.org/web/20240928194118/https://www.geeksforgeeks.org/psycopg2-insert-dictionary-as-json/
Open In App

Psycopg2 – Insert dictionary as JSON

Last Updated : 31 Aug, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we are going to see how to insert a dictionary as JSON using Psycopg2 and Python.

Python dict objects can be or rather should be stored in database tables as JSON datatype. Since most of the SQL databases have a JSON datatype. This allows using these objects or key-value pairs in the front-end or in an API to process the request that is being placed from them respectively.

Setting up a PostgreSQL Database and Table:

Let us create a schema in PostgreSQL and add a table to it with at least one JSON type column. We can use the following SQL script to create the same.

In the above SQL script, we have created a schema name “geeks”. A table “json_example ” is created in the schema which consists of two columns, one which is the primary key has column name “id” whereas the other column has name “json_col ” which is of type JSON.

Inserting a python dict object in PostgreSQL table using psycopg2 library:

Python




import json
import psycopg2
  
# SAVE THE DB CONFIG IN A DICT OBJECT
DATABASE_CONFIG = {
    "database": "geeks",
    "user": "postgres",
    "password": "password",
    "host": "localhost",
    "port":  5432,
}
  
  
def get_connection():
  
    # RETURN THE CONNECTION OBJECT
    return psycopg2.connect(
        database=DATABASE_CONFIG.get('database'),
        user=DATABASE_CONFIG.get('user'),
        password=DATABASE_CONFIG.get('password'),
        host=DATABASE_CONFIG.get('host'),
        port=DATABASE_CONFIG.get('port'),
    )
  
  
def dict_to_json(value: dict):
  
    # CONVERT DICT TO A JSON STRING AND RETURN
    return json.dumps(value)
  
  
def insert_value(id: str, json_col: str, conn):
  
    # CREATE A CURSOR USING THE CONNECTION OBJECT
    curr = conn.cursor()
  
    # EXECUTE THE INSERT QUERY
    curr.execute(f'''
        INSERT INTO
            json_table(id, json_col) 
        VALUES
            ('JSON001', '{json_col}')
    ''')
  
    # COMMIT THE ABOVE REQUESTS
    conn.commit()
  
    # CLOSE THE CONNECTION
    conn.close()
  
  
def main():
  
    # CREATE A PSYCOPG2 CONNECTION
    conn = get_connection()
  
    # CREATE A PYTHON DICT OBJECT FOR JSON COL
    dict_obj = {
        "name": "Amit Pathak",
        "skill": "Python",
        "experience": 4
    }
  
    # CONVERT DICT OBJECT TO JSON STRING
    json_obj = dict_to_json(value=dict_obj)
  
    # INSERT VALUES IN THE DATABASE TABLE
    insert_value(id='JSON001', json_col=json_obj,
                 conn=conn)
  
if __name__ == '__main__':
    main()


After running the above python file, we can head to the pgAdmin to view the following output in json_table table under public schema. You can run the following SQL script in the Query tool –

$ SELECT * FROM json_table;

Output viewed in pgAdmin

Explanation:

The above code is written in a functional format for a better representation of the underlying steps that take place in the entire process. The get_connection() function returns the connection object to the PostgreSQL table using which we can establish a connection to the database for our operations. If the connection object cannot be established, it will return False. Now, we have a python dict object created in variable name dict_obj. We will insert this dict object into the database. But, before we insert this dict object, we need to convert the object in JSON format since the database understands JSON format and not the python dict object. Python’s in-built module json is used to convert the dict object in a JSON string format using the dumps() method. Now that we have the JSON string and the connection object, we can insert the data in the database table json_table. For this purpose, we have created a function names insert_value() which takes in 3 arguments, namely, id for the value to be inserted in id column, json_col for the value that needs to be inserted in the json_col column, and the conn parameter for providing the connection object created earlier. We can see that The insert_value() function runs the usual INSERT SQL script using the connection object. The connection is closed once the data is been inserted to the table.

Using the psycopg2 Json adaptation

The following code demonstrates how psycopg2’s Json adaptation can be used instead of the standard json.dumps(). In order to pass a Python object to the database as a query argument, you can use the Json adapter imported from psycopg2.extras.

Python




import psycopg2
from psycopg2.extras import Json
  
  
# CREATE A PSYCOPG2 CONNECTION
conn = psycopg2.connect(**{
    "database" : "geeks",
    "user"     : "postgres",
    "password" : "password",
    "host"     : "localhost",
    "port"     :  5432,
})
  
# CREATE DICT OBJECT TO BE INSERTED TO DB
dict_obj = {
    "name": "Suhas Hegde",
    "skill": "PL/SQL",
    "experience": 3
}
  
# CREATE A CURSOR USING THE CONNECTION OBJECT
curr = conn.cursor()
  
# EXECUTE THE INSERT QUERY
curr.execute(f'''
    INSERT INTO
        json_table(id, json_col) 
    VALUES
        ('JSON002', %s)
''', [Json(dict_obj)])
  
# COMMIT THE REQUESTS IN QUEUE
conn.commit()
  
# CLOSE THE CONNECTION
conn.close()


Output:

Output viewed in pgAdmin

In the above code, we are trying to insert a new JSON entry with id as JSON002. The entire process remains the same as in the earlier code except for the fact that we have used psycopg2.extras.Json instead of json.dumps.



Similar Reads

Comparing psycopg2-binary vs psycopg2 in Python
When working with PostgreSQL databases in Python, one of the most critical decisions is choosing the right library for database connectivity. psycopg2 is the go-to library for many developers due to its efficiency and extensive feature set. However, there's often confusion between psycopg2 and its sibling, psycopg2-binary. This article will demysti
7 min read
Insert Python Dictionary in PostgreSQL using Psycopg2
In this article, we are going to see how to insert a Python dictionary in PostgreSQL using Psycopg2. We can insert a python dictionary by taking the dictionary keys as column names and values as dictionary values. We import the Psycopg2 package and form a connection to the PostgreSQL database using psycopg2.connect() method. First, let's create a t
2 min read
Python Psycopg2 - Insert multiple rows with one query
This article is about inserting multiple rows in our table of a specified database with one query. There are multiple ways of executing this task, let's see how we can do it from the below approaches. Method 1: Inserting Values through Naive method In this method, we import the psycopg2 package and form a connection using the psycopg2.connect() met
4 min read
Read and insert bytea columns using psycopg2
PostgreSQL is an open-source database management system. It allows users to store data in various formats, including bytea (binary data) format. psycopg2 is a popular Python library that provides an interface for working with PostgreSQL databases. Users can read and insert bytea columns using psycopg2. Bytea: Bytea is a PostgreSQL data type that is
3 min read
Perform Insert Operations with psycopg2 in Python
psycopg2 is a widely used Python library designed to facilitate communication with PostgreSQL databases, offering a robust and efficient way to perform various database operations. It is a powerful and flexible connector, which allows Python applications to execute SQL commands and handle data seamlessly. Insert operation is one of the core operati
10 min read
Psycopg2 - Return dictionary like values
In this article, we will discuss how to use psycopg2 to return dictionary-like values. We can return dictionary-like values by using the psycopg2 PostgreSQL driver with and without using the extras module and both will be discussed in this article. psycopg.extras provide Miscellaneous goodies for Psycopg2. It holds helper functions and classes unti
3 min read
Python | Getting started with psycopg2-PostGreSQL
PostgreSQL is a powerful, open source object-relational database system. PostgreSQL runs on all major operating systems. PostgreSQL follows ACID property of DataBase system and has the support of triggers, updatable views and materialized views, foreign keys. To connect PostgreSQL we use psycopg2 . It is the best and most friendly Database adapter
1 min read
Do loop in Postgresql Using Psycopg2 Python
In this article, we use psycopg2 to loop through all data points using psycopg2 function in Python. We will first connect our PostgreSQL database using psycopg2.connect method, and pass the connection parameters such as the host, database, user, and password. Then we will create a cursor using the conn.cursor method. The cur.execute method, passes
4 min read
Python psycopg2 - Read Image
Psycopg2 is the most widely used PostgreSQL database adapter for Python. The creation, update, modification, and deletion of PostgreSQL databases and tables, as well as the execution of queries and the retrieval of results, are all supported by it. This library also supports transaction management, server-side cursors, and other advanced features.
9 min read
How to Install psycopg2 Binary Module in Python ?
psycopg2 is the most popular PostgreSQL database adapter for the Python programming language. It is a DB API 2.0 compliant PostgreSQL driver that is actively developed. It is designed for heavily multi-threaded applications that create and destroy lots of cursors and create a large number of "INSERTs" or "UPDATEs". Installation: To install this mod
1 min read
Get psycopg2 count(*) number of results
In this article, we are going to see how to get psycopg2 count(*) number of results. psycopg2 count(*) returns the number of rows from a database table holding some specific conditions. If no condition is given then it returns the total number of tuples present in the relation. Syntax: SELECT COUNT(*) FROM table_name; # to return total no. of rows
2 min read
Chain multiple statements within Psycopg2
In this tutorial, we will see how to chain multiple statements with psycopg2 which is a PostgreSQL database adapter for Python. Chaining is supported by most SQL databases and can be used in various types of SQL clients, such as command-line interfaces, web-based management interfaces, and programming language libraries like psycopg2. let's underst
8 min read
Get column names from PostgreSQL table using Psycopg2
This article is an illustration of how to extract column names from PostgreSQL table using psycopg2 and Python. Used table for demonstration: Example 1: First, we connect the PostgreSQL database using psycopg2.connect() method, then we create a cursor using cursor() method, after that we use the cursor() then extract the first element from it using
1 min read
Executing SQL query with Psycopg2 in Python
In this article, we are going to see how to execute SQL queries in PostgreSQL using Psycopg2 in Python. Psycopg2 is a PostgreSQL database driver, it is used to perform operations on PostgreSQL using python, it is designed for multi-threaded applications. SQL queries are executed with psycopg2 with the help of the execute() method. It is used to Exe
2 min read
Python Psycopg2 - Concatenate columns to new column
In this article, we are going to see how to concatenate multiple columns of a table in a PostgreSQL database into one column. To concatenate two or more columns into one, PostgreSQL provides us with the concat() function. Table for demonstration: In the below code, first, a connection is formed to the PostgreSQL database 'geeks' by using the connec
2 min read
Python Psycopg2 - Inserting array of strings
In this article, we will be looking at the multiple approaches to inserting an array of strings in pyscopg2/Postgres in the python programming language., Method 1: Naive method In this example, we form a connection to the classroom database using psycopg2.connect() method, we then create a cursor using conn.cursor() method. We then insert the value
2 min read
Introduction to Psycopg2 module in Python
Psycopg is the most popular PostgreSQL adapter used in Python. Its works on the principle of the whole implementation of Python DB API 2.0 along with the thread safety (the same connection is shared by multiple threads). It is designed to perform heavily multi-threaded applications that usually create and destroy lots of cursors and make a large nu
4 min read
Python Psycopg2 - Getting ID of row just inserted
In this article, we are going to see how to get the ID of the row just inserted using pyscopg2 in Python Establishing a connection to the PostgreSQL serverIn order to establish a connection to the PostgreSQL server, we will make use of the pscopg2 library in python. You can install psycopg2 using the following command: pip install psycopg2 After in
3 min read
Bulk update of rows in Postgres DB using psycopg2
PostgreSQL or Postgres is an open-source, relational, SQL complaint, database management system. It allows, the developers, to create complex applications, supporting SQL and JSON querying. It safely stores, and, scales workloads. Psycopg2 is a driver, that is used, for interacting, with Postgres data, using the Python scripting language. It is, us
6 min read
Multiple Postgres databases in psycopg2
PostgreSQL is the most powerful open-source object-relational database management system. Psycopg2 is the most popular PostgreSQL database adapter for Python language. It simply allows you to work with multiple databases in the same program at the same time. This indicates that you can easily switch between two different databases and can perform v
4 min read
Python PostgreSQL Connection Pooling Using Psycopg2
In this article, We will cover the basics of connection pooling using connection pooling in Python applications, and provide step-by-step instructions on how to implement connection pooling using Psycopg2. Whether you are building a small-scale application or a large-scale enterprise application, understanding how to implement connection pooling wi
6 min read
Python Database Optimization with Psycopg2 and Multiprocessing
This article will provide a succinct overview of the fundamental utilization of the Psycopg2 module and the Multiprocessing module in Python. It will cover how Psycopg2 operates independently and in conjunction with multiprocessing. Psycopg2 and Its Role in Database OperationsAccording to PyPi's documentation for Psycopg2, it is designed to be used
6 min read
How to Fix 'NoSuchModuleError: Can't Load Plugin: sqlalchemy.dialects.postgres.psycopg2' in Python
SQLAlchemy is a powerful SQL toolkit and Object-Relational Mapping (ORM) library for Python. It facilitates interaction with various databases using Python code. However, while working with SQLAlchemy, developers may encounter the error: NoSuchModuleError: Can't Load Plugin: sqlalchemy.dialects.postgres.psycopg2. This error indicates a problem with
3 min read
How to Handle 'psycopg2.errors.invaliddatetimeformat' Error in Python
The psycopg2 library is a popular PostgreSQL database adapter for Python. While working with databases, it's common to encounter various types of errors. One such error is psycopg2.errors.InvalidDatetimeFormat. This article will delve into what causes the psycopg2.errors.InvalidDatetimeFormat error and provide practical solutions with correct code
3 min read
How to Fix 'ModuleNotFoundError: No Module Named psycopg2' in Python
The psycopg2 package in Python interacts with PostgreSQL databases, providing an interface for executing SQL queries and managing database connections. If you encounter the 'ModuleNotFoundError: No Module Named psycopg2' error, it typically means that the package is not installed in your Python environment. This article will teach us to Fix 'Module
3 min read
How to Fix 'psycopg2 OperationalError' in Python
The psycopg2 is a popular PostgreSQL adapter for the Python programming language. It's widely used in web applications for database interactions. However, while working with psycopg2, you may encounter the OperationalError error. This error typically occurs due to issues related to the database connection or operation. In this article, we will disc
3 min read
How to Fix 'psycopg2 OperationalError: SSL SYSCALL Error: EOF Detected' in Python
Developers occasionally encounter the error psycopg2 OperationalError: SSL SYSCALL Error: EOF Detected. This error can be frustrating, as it often indicates an issue with the SSL connection between your application and the PostgreSQL server. In this article, we will explore what this error means, common causes, and how to fix it with practical code
3 min read
How to Fix 'psycopg2.InterfaceError: Connection Already Closed' in Python
When working with PostgreSQL databases in Python, the psycopg2 library is a popular choice for establishing connections and executing queries. However, developers often encounter the psycopg2.InterfaceError: Connection Already Closed error, which can disrupt database operations. This article aims to explain the causes behind this error and provide
4 min read
How to Set Timeouts in psycopg2 using Python
Setting timeouts in psycopg2 is crucial for ensuring your application doesn't hang indefinitely while waiting for a response from the PostgreSQL database. Timeouts help maintain application performance and reliability by ensuring that long-running queries or connection issues do not negatively impact the overall user experience. In this article, we
3 min read
How to Fix 'pg_config is Required to Build psycopg2 from Source' in Python
During installation or while building psycopg2 from source, you might encounter an error that states 'pg_config is required to build psycopg2 from source'. This article will explain what this error means, the common reasons it occurs, and how to resolve it with proper code examples. Table of Content What Does 'pg_config is Required to Build psycopg
4 min read
Practice Tags :