0
0
RedisHow-ToBeginner · 3 min read

How to Store JSON in Redis: Simple Guide

You can store JSON in Redis by saving it as a string using the SET command or by using the RedisJSON module which allows storing and querying JSON natively with commands like JSON.SET. The RedisJSON module provides better support for JSON data manipulation inside Redis.
📐

Syntax

To store JSON as a string in Redis, use the SET command with the key and JSON string. For example, SET key "{\"name\":\"John\",\"age\":30}". If you use the RedisJSON module, you can use JSON.SET key . '{"name":"John","age":30}' to store JSON natively.

The SET command stores data as plain text, while JSON.SET stores and manages JSON data with structure.

redis
SET user:1 "{\"name\":\"John\",\"age\":30}"  

JSON.SET user:1 . '{"name":"John","age":30}'
Output
OK OK
💻

Example

This example shows how to store and retrieve JSON data as a string and using RedisJSON module.

redis
127.0.0.1:6379> SET user:1 "{\"name\":\"John\",\"age\":30}"
OK
127.0.0.1:6379> GET user:1
"{\"name\":\"John\",\"age\":30}"

# Using RedisJSON module
127.0.0.1:6379> JSON.SET user:2 . '{"name":"Jane","age":25}'
OK
127.0.0.1:6379> JSON.GET user:2
'{"name":"Jane","age":25}'
Output
"{\"name\":\"John\",\"age\":30}" '{"name":"Jane","age":25}'
⚠️

Common Pitfalls

  • Storing JSON as plain strings means Redis does not understand the structure, so you cannot query or update parts of the JSON easily.
  • Forgetting to escape quotes properly when using SET can cause syntax errors.
  • Using RedisJSON commands without the module installed will cause errors.
  • Not using JSON.GET to retrieve JSON stored by RedisJSON can return unexpected results.
redis
Wrong:
SET user:3 {"name":"Bob","age":40}
# Missing quotes around JSON string causes error

Right:
SET user:3 "{\"name\":\"Bob\",\"age\":40}"
📊

Quick Reference

Use SET key "json_string" to store JSON as text.
Use RedisJSON module commands like JSON.SET and JSON.GET for native JSON support.
Always escape quotes in JSON strings when using SET.

Key Takeaways

Store JSON as a string with SET or use RedisJSON module for native JSON support.
Escape quotes properly when storing JSON as a string to avoid errors.
RedisJSON allows querying and updating parts of JSON data inside Redis.
Without RedisJSON, Redis treats JSON as plain text with no structure awareness.