rejson (Deprecated: use redis-py for RedisJSON features)

0.5.6 · deprecated · verified Thu Apr 16

rejson-py is a Python client library for RedisJSON, a Redis module that implements the JSON data type. It provides an extended interface to redis-py, offering on-the-fly serialization and deserialization of JSON objects. As of `redis-py` version 4.0.0, this library is deprecated, and its functionalities have been integrated directly into the `redis-py` client. The `rejson` package is currently at version 0.5.6 and has a very slow release cadence, with the last update in November 2021.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic operations (set, get, update, append) using the `rejson-py` client. It requires a running Redis server with the RedisJSON module loaded. A commented-out section shows the equivalent approach using the recommended `redis-py` client (v4.0.0+).

import os
from rejson import Client, Path
import json

# Ensure a RedisJSON server is running, e.g., via Docker:
# docker run -d -p 6379:6379 redislabs/rejson:latest

REDIS_HOST = os.environ.get('REDIS_HOST', 'localhost')
REDIS_PORT = int(os.environ.get('REDIS_PORT', 6379))

try:
    # Using the deprecated rejson-py client
    rj = Client(host=REDIS_HOST, port=REDIS_PORT)

    obj = {
        'name': 'Alice',
        'age': 30,
        'city': 'New York',
        'hobbies': ['reading', 'hiking'],
        'address': {'street': '123 Main St', 'zip': '10001'}
    }

    # Set a JSON object at the root path
    rj.jsonset('user:1', Path.rootPath(), obj)
    print(f"Set JSON for user:1: {obj}")

    # Get a specific field
    name = rj.jsonget('user:1', Path('.name'))
    print(f"User's name: {name}")

    # Update a field
    rj.jsonset('user:1', Path('.age'), 31)
    updated_age = rj.jsonget('user:1', Path('.age'))
    print(f"Updated user's age: {updated_age}")

    # Append to an array
    rj.jsonarrappend('user:1', Path('.hobbies'), 'coding')
    hobbies = rj.jsonget('user:1', Path('.hobbies'))
    print(f"User's hobbies after appending: {hobbies}")

    # --- Recommended modern approach using redis-py (v4.0.0+) ---
    # from redis import Redis
    # r = Redis(host=REDIS_HOST, port=REDIS_PORT)
    # r.json().set('user:2', Path.root_path(), {'email': 'bob@example.com'})
    # email = r.json().get('user:2', Path('.email'))
    # print(f"User 2 email (via redis-py): {email}")

except Exception as e:
    print(f"An error occurred: {e}")
    print("Please ensure a Redis server with the ReJSON module is running and accessible.")

view raw JSON →