How to Store JSON in Redis

JavaScript Object Notation, or JSON, is a super fast and lightweight data exchange format widely adopted. It is human-readable while still providing flexibility for both machines and users.

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.


To better follow along with this tutorial, ensure you:

  1. Have the latest version of the Redis server installed on your local machine.
  2. 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:> SET user_info '{"id":3,"first_name":"Valida","last_name":"Lindop","email":"[email protected]","ip_address":""}'

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:> GET user_info

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:

To add a new JSON document using the JSON module, run the command:> JSON.SET user_info . '{"id":1}'

The above should add a new key holding a JSON document.

We can fetch the JSON using GET as:> JSON.GET user_info

To get the type of an JSON entity, we can run:> JSON.TYPE user_info .id

True, id is holding an integer type.

To delete a JSON document, run:> JSON.DEL user_info
(integer) 1


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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list