How to Use the Redis to Store Json Data
Published: 2022-01-16 04:51:26

[RedisJSON](https://oss.redis.com/redisjson/) is a source-available Redis module that lets you store, manipulate, and query JSON documents in Redis. The standard Redis Python client (v4.0 or greater) supports all of the features of RedisJSON, and in this tutorial, we'll see how to get started with them.

## Getting started with RedisJSON

To run the examples below, you'll need to ensure that you have an instance of Redis that includes RedisJSON. If you're developing locally, you can use Docker for this:

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

## Verify that the RedisJSON module is loaded

Connect to Redis using `redis-cli`, and run the `info modules` command:

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

Ensure that you're running RedisJSON v2.0 or greater (here indicated as `20004`).

## Load the latest version of `redis-py`

You'll need `redis-py` version 4.0 or later. If you're using `pipenv`, you can install the client library like so:

```bash
pipenv install redis
```

Then you can run `pipenv graph` to make sure you're running the latest version of the client:

```
$ pipenv graph
redis==4.0.2
```

## Storing JSON in Redis

Let's consider a simple JSON document structure representing a user:

```
 {
  "name": "Jane",
  "age": 33,
  "location: "Chawton"
 }
```

Here's the Python code to store this document in Redis using RedisJSON:

```python
import redis
from redis.commands.json.path import Path

client = redis.Redis(host='localhost', port=6379, db=0)

jane = {
     'name': "Jane", 
     'Age': 33, 
     'Location': "Chawton"
   }

client.json().set('person:1', Path.rootPath(), jane)

result = client.json().get('person:1')
print(result)
```

In the code above, we first connect to Redis and store a reference to the connection in the `client` variable.

Next, we create a Python dictionary to represent a person object.

And finally, we store the object in Redis using the `json().set()` method. The first argument, `person:1` is the name of the key that will reference the JSON. The second argument is a JSON path. We use `Path.rootPath()`, as this is a new object. Finally, we pass in the Python dictionary, which will be serialized to JSON.

To retrieve the JSON object, we run `json().get()`, passing in the key. The result is a Python dictionary representing the JSON object stored in Redis.

### Run the code

If you copy the code above into a file called `main.py`, you can run the code like so:

```bash
$ pipenv python run main.py
```

## Verify that the JSON document has been added to Redis

Start `redis-cli` to connect to your Redis instance. Then run the following command:

```bash
localhost:6379> json.get person:1
"{\"name\":\"Jane\",\"Age\":33,\"Location\":\"Chawton\"}"
```

## Fetching specific fields from a JSON document

You can use RedisJSON to fetch specific fields from a document by specifying a path. For example, here's how to return only the `name` field:

```python
name = client.json().get('person:1', Path('.name'))
print(name)
```
This code will print the string "Jane".

You can execute the same query from the command line:

```bash
localhost:6379> json.get person:1 '.name'
"\"Jane\""
```

### References

- [Modeling JSON Documents with Redis and Java](https://developer.redis.com/howtos/redisjson/using-python)
- [How to cache JSON data in Redis with Node.js](https://developer.redis.com/howtos/redisjson/using-nodejs)
- [How to cache JSON data in Redis with Ruby](https://developer.redis.com/howtos/redisjson/using-ruby)