Redis

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.

Requirements:

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:

 127.0.0.1:6379> SET user_info '{"id":3,"first_name":"Valida","last_name":"Lindop","email":"[email protected]","ip_address":"140.207.199.111"}'
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:

127.0.0.1:6379> GET user_info
"{"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:

127.0.0.1:6379> JSON.SET user_info . '{"id":1}'
OK

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

We can fetch the JSON using GET as:

127.0.0.1:6379> JSON.GET user_info
"{"id":1}

To get the type of an JSON entity, we can run:

127.0.0.1:6379> JSON.TYPE user_info .id
"integer"

True, id is holding an integer type.

To delete a JSON document, run:

127.0.0.1:6379> JSON.DEL user_info
(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.

https://oss.redis.com/redisjson/

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