How to store JSON documents in Redis with Python

RedisJSON is a Redis module that lets you store JSON documents in Redis. It is a JSON data type for Redis that lets you to fetch or modify a specific element in the document tree, without retrieving (or internally even parsing) the document. Its Python client even lets you store python dicts and convert them to JSON automatically.

RedisJSON Python Client#

The 'rejson-py' is a package that allows storing, updating and querying objects as JSON documents in a Redis database that is extended with the RedisJSON module. The package extends redis-py's interface with RedisJSON's API, and performs on-the-fly serialization/deserialization of objects to/from JSON.

Follow the steps below to get started with RedisJSON with Python:

Step 1. Run RedisJSON Docker container#

docker run -p 6379:6379 --name redis-redisjson redislabs/rejson:latest

Step 2. Verify if RedisJSON module is loaded#

redis-cli
127.0.0.1:6379> info modules
# Modules
module:name=ReJSON,ver=10007,api=1,filters=0,usedby=[],using=[],options=[]
127.0.0.1:6379>

Step 3. Storing the JSON document#

Let us consider a simple JSON document structure:

employee
{
"name": "Paul John",
"age": 25,
"location: "USA"
}

Below is a python code to store the JSON document into Redis:

from rejson import Client, Path
rj = Client(host='localhost', port=6379, decode_responses=True)
employee = {
'name': "Paul",
'Age': '25',
'Location': "USA"
}
rj.jsonset('employee', Path.rootPath(), employee)

In the code above, we use JSON.GET to extract the JSON elements. Save the above file as "employee.py".

Step 4. Load Redis Module#

pip install rejson

Step 5. Execute the python script#

python3 employee.py

Step 6. Verify the JSON document added to Redis#

Command:
127.0.0.1:6379> JSON.GET employee
Result:
"{\"name\":\"Paul\",\"Age\":\"25\",\"Location\":\"USA\"}"
127.0.0.1:6379>

Step 7. Fetching the specific fields within JSON document#

It's possible to fetch specific field within JSON element. Let us modify the above code and add "address" field as shown below:

from rejson import Client, Path
rj = Client(host='localhost', port=6379, decode_responses=True)
employee = {
'name': "Paul",
'Age': '25',
'address': {
'location': "USA"
}
}
rj.jsonset('employee', Path.rootPath(), employee)
rj.jsonget('employee', Path('.address.location'))

In the above example, the code tries to fetch only the location under the address field.

Step 8. Verifying the results#

Command:
127.0.0.1:6379> JSON.GET employee .address.location
Results:
"\"USA\""

References#