Learning to work with JSON is a requirement when building any non-trivial application. It is there helpful to know how to store JSON in Redis.
Requirements:
To better follow along with this tutorial, ensure you:
- Have the latest version of the Redis server installed on your local machine.
- Are using the native Redis-CLI for maximum compatibility and output.
Method 1 – Pre-Serialized Data
The simplest method to store JSON is to take pre-serialized data and store it as a native Redis key.
For example:
OK
Here, we use a Redis string to hold JSON data. However, it works for simple use cases; a few issues arise from using this method on the extensive use cases.
There is no direct way to manipulate the values. Therefore, if you need to update any value, you will have to set the key from scratch.
During read/write, serialization uses more resources.
Since Redis does not compress the data you add to it, JSON will add a heavy memory overhead.
Third, the output from JSON as a serialized object is not very readable.
For example:
"{"id":3,"first_name":"Valida","last_name":"Lindop","email":"vlindop2@eventbrite.com","ip_address":"140.207.199.111"}"
Method 2 – RedisJSON Module
The second and most viable method to use JSON in your Redis database is the RedisJSON module.
We will not cover the installation in this article. Instead, you can check the resource provided below:
https://oss.redis.com/redisjson/
To add a new JSON document using the JSON module, run the command:
OK
The above should add a new key holding a JSON document.
We can fetch the JSON using GET as:
"{"id":1}
To get the type of an JSON entity, we can run:
"integer"
True, id is holding an integer type.
To delete a JSON document, run:
(integer) 1
Closing
And with that, you have two ways to store JSON data in your Redis database. Keep practicing and check other Linuxhint tutorials to expand your knowledge.