0
# JSON Operations
1
2
JSON path-based operations for storing, retrieving, and manipulating JSON documents in Redis using RedisJSON. Provides type-safe operations for working with complex JSON data structures with path-based access.
3
4
## Capabilities
5
6
### Core JSON Operations
7
8
Basic JSON document operations for storing and retrieving JSON data.
9
10
```typescript { .api }
11
/**
12
* Get JSON data from a key
13
* @param key - The JSON key
14
* @param options - Optional get parameters (path, indent, newline, space)
15
* @returns The JSON value at the specified path, or null if not found
16
*/
17
function get(key: RedisArgument, options?: JsonGetOptions): Promise<RedisJSON | null>;
18
19
/**
20
* Set JSON data at a key
21
* @param key - The JSON key
22
* @param path - JSON path (default: root '$')
23
* @param value - JSON value to set
24
* @param options - Optional set conditions (NX, XX)
25
* @returns 'OK' if successful, null if condition not met
26
*/
27
function set(key: RedisArgument, path: string, value: RedisJSON, options?: JsonSetOptions): Promise<SimpleStringReply<'OK'> | null>;
28
29
/**
30
* Get JSON data from multiple keys
31
* @param keys - Array of JSON keys
32
* @param path - JSON path to retrieve
33
* @returns Array of JSON values (null for non-existent keys/paths)
34
*/
35
function mGet(keys: RedisArgument[], path: string): Promise<ArrayReply<RedisJSON | null>>;
36
37
/**
38
* Set JSON data at multiple keys
39
* @param keyPathValues - Array of key-path-value tuples
40
* @returns 'OK'
41
*/
42
function mSet(keyPathValues: Array<[key: RedisArgument, path: string, value: RedisJSON]>): Promise<SimpleStringReply<'OK'>>;
43
44
/**
45
* Delete JSON path from key
46
* @param key - The JSON key
47
* @param path - JSON path to delete (default: root '$')
48
* @returns Number of paths deleted
49
*/
50
function del(key: RedisArgument, path?: string): Promise<NumberReply>;
51
52
/**
53
* Get the type of JSON value at path
54
* @param key - The JSON key
55
* @param path - JSON path (default: root '$')
56
* @returns The JSON type ('null', 'boolean', 'number', 'string', 'object', 'array')
57
*/
58
function type(key: RedisArgument, path?: string): Promise<BlobStringReply | null>;
59
60
interface JsonGetOptions {
61
/** JSON path to retrieve */
62
path?: string | string[];
63
/** Indentation string for pretty printing */
64
indent?: string;
65
/** Newline string for pretty printing */
66
newline?: string;
67
/** Space string for pretty printing */
68
space?: string;
69
}
70
71
interface JsonSetOptions {
72
/** Set condition: 'NX' (only if doesn't exist) or 'XX' (only if exists) */
73
condition?: 'NX' | 'XX';
74
/**
75
* @deprecated Use `{ condition: 'NX' }` instead
76
* Only set if path does not exist
77
*/
78
NX?: boolean;
79
/**
80
* @deprecated Use `{ condition: 'XX' }` instead
81
* Only set if path exists
82
*/
83
XX?: boolean;
84
}
85
86
type RedisJSON = string | number | boolean | null | RedisJSON[] | { [key: string]: RedisJSON };
87
```
88
89
**Usage Examples:**
90
91
```typescript
92
import { createClient } from "redis";
93
94
const client = createClient();
95
await client.connect();
96
97
// Basic JSON operations
98
await client.json.set("user:1", "$", {
99
name: "Alice",
100
age: 30,
101
email: "alice@example.com",
102
preferences: {
103
theme: "dark",
104
notifications: true
105
},
106
tags: ["developer", "nodejs"]
107
});
108
109
// Get entire document
110
const user = await client.json.get("user:1");
111
// { name: "Alice", age: 30, email: "alice@example.com", ... }
112
113
// Get specific path
114
const name = await client.json.get("user:1", { path: "$.name" }); // "Alice"
115
const age = await client.json.get("user:1", { path: "$.age" }); // 30
116
117
// Set nested property
118
await client.json.set("user:1", "$.preferences.theme", "light");
119
120
// Multi-get from multiple keys
121
const users = await client.json.mGet(["user:1", "user:2"], "$.name");
122
// ["Alice", null] (if user:2 doesn't exist)
123
124
// Delete path
125
await client.json.del("user:1", "$.tags[1]"); // Remove second tag
126
127
// Get type information
128
const type = await client.json.type("user:1", "$.age"); // "number"
129
```
130
131
### String Operations
132
133
JSON string manipulation operations.
134
135
```typescript { .api }
136
/**
137
* Get length of JSON string at path
138
* @param key - The JSON key
139
* @param path - JSON path (default: root '$')
140
* @returns String length, or array of lengths for multiple paths
141
*/
142
function strlen(key: RedisArgument, path?: string): Promise<NumberReply | ArrayReply<NumberReply | null>>;
143
144
/**
145
* Append string to JSON string at path
146
* @param key - The JSON key
147
* @param path - JSON path
148
* @param value - String value to append
149
* @returns New string length, or array of lengths for multiple paths
150
*/
151
function strAppend(key: RedisArgument, path: string, value: RedisArgument): Promise<NumberReply | ArrayReply<NumberReply>>;
152
```
153
154
**Usage Examples:**
155
156
```typescript
157
// String operations
158
await client.json.set("doc", "$", { message: "Hello" });
159
160
// Get string length
161
const length = await client.json.strlen("doc", "$.message"); // 5
162
163
// Append to string
164
await client.json.strAppend("doc", "$.message", " World");
165
const newLength = await client.json.strlen("doc", "$.message"); // 11
166
167
const message = await client.json.get("doc", { path: "$.message" }); // "Hello World"
168
```
169
170
### Numeric Operations
171
172
JSON numeric manipulation operations.
173
174
```typescript { .api }
175
/**
176
* Increment JSON number at path
177
* @param key - The JSON key
178
* @param path - JSON path
179
* @param number - Number to add
180
* @returns New number value, or array of values for multiple paths
181
*/
182
function numIncrBy(key: RedisArgument, path: string, number: number): Promise<BlobStringReply | ArrayReply<BlobStringReply>>;
183
184
/**
185
* Multiply JSON number at path
186
* @deprecated since JSON version 2.0
187
* @param key - The JSON key
188
* @param path - JSON path
189
* @param number - Number to multiply by
190
* @returns New number value, or array of values for multiple paths
191
*/
192
function numMultBy(key: RedisArgument, path: string, number: number): Promise<BlobStringReply | ArrayReply<BlobStringReply>>;
193
194
/**
195
* Toggle JSON boolean at path
196
* @param key - The JSON key
197
* @param path - JSON path
198
* @returns New boolean value as array
199
*/
200
function toggle(key: RedisArgument, path: string): Promise<ArrayReply<BooleanReply>>;
201
```
202
203
**Usage Examples:**
204
205
```typescript
206
// Numeric operations
207
await client.json.set("stats", "$", {
208
views: 100,
209
likes: 50,
210
active: true
211
});
212
213
// Increment number
214
await client.json.numIncrBy("stats", "$.views", 10);
215
const views = await client.json.get("stats", { path: "$.views" }); // 110
216
217
// Multiply number (deprecated but still available)
218
await client.json.numMultBy("stats", "$.likes", 2);
219
const likes = await client.json.get("stats", { path: "$.likes" }); // 100
220
221
// Toggle boolean
222
await client.json.toggle("stats", "$.active");
223
const active = await client.json.get("stats", { path: "$.active" }); // false
224
```
225
226
### Array Operations
227
228
JSON array manipulation operations.
229
230
```typescript { .api }
231
/**
232
* Append values to JSON array at path
233
* @param key - The JSON key
234
* @param path - JSON path
235
* @param values - Values to append
236
* @returns New array length, or array of lengths for multiple paths
237
*/
238
function arrAppend(key: RedisArgument, path: string, ...values: RedisJSON[]): Promise<NumberReply | ArrayReply<NumberReply>>;
239
240
/**
241
* Find index of value in JSON array
242
* @param key - The JSON key
243
* @param path - JSON path
244
* @param value - Value to search for
245
* @param start - Start index (optional)
246
* @param stop - Stop index (optional)
247
* @returns Index of value, or -1 if not found
248
*/
249
function arrIndex(key: RedisArgument, path: string, value: RedisJSON, start?: number, stop?: number): Promise<NumberReply | ArrayReply<NumberReply>>;
250
251
/**
252
* Insert values into JSON array at index
253
* @param key - The JSON key
254
* @param path - JSON path
255
* @param index - Index to insert at
256
* @param values - Values to insert
257
* @returns New array length, or array of lengths for multiple paths
258
*/
259
function arrInsert(key: RedisArgument, path: string, index: number, ...values: RedisJSON[]): Promise<NumberReply | ArrayReply<NumberReply>>;
260
261
/**
262
* Get length of JSON array at path
263
* @param key - The JSON key
264
* @param path - JSON path (default: root '$')
265
* @returns Array length, or array of lengths for multiple paths
266
*/
267
function arrLen(key: RedisArgument, path?: string): Promise<NumberReply | ArrayReply<NumberReply | null>>;
268
269
/**
270
* Remove and return element from JSON array
271
* @param key - The JSON key
272
* @param path - JSON path (default: root '$')
273
* @param index - Index to pop from (default: -1, last element)
274
* @returns Popped element, or array of elements for multiple paths
275
*/
276
function arrPop(key: RedisArgument, path?: string, index?: number): Promise<BlobStringReply | ArrayReply<BlobStringReply | null>>;
277
278
/**
279
* Trim JSON array to specified range
280
* @param key - The JSON key
281
* @param path - JSON path
282
* @param start - Start index (inclusive)
283
* @param stop - Stop index (inclusive)
284
* @returns New array length, or array of lengths for multiple paths
285
*/
286
function arrTrim(key: RedisArgument, path: string, start: number, stop: number): Promise<NumberReply | ArrayReply<NumberReply>>;
287
```
288
289
**Usage Examples:**
290
291
```typescript
292
// Array operations
293
await client.json.set("doc", "$", {
294
tags: ["redis", "json"],
295
scores: [10, 20, 30]
296
});
297
298
// Append to array
299
await client.json.arrAppend("doc", "$.tags", "nodejs", "typescript");
300
let tags = await client.json.get("doc", { path: "$.tags" });
301
// ["redis", "json", "nodejs", "typescript"]
302
303
// Find array index
304
const index = await client.json.arrIndex("doc", "$.tags", "nodejs"); // 2
305
306
// Insert into array
307
await client.json.arrInsert("doc", "$.tags", 1, "database");
308
tags = await client.json.get("doc", { path: "$.tags" });
309
// ["redis", "database", "json", "nodejs", "typescript"]
310
311
// Get array length
312
const length = await client.json.arrLen("doc", "$.tags"); // 5
313
314
// Pop from array
315
const popped = await client.json.arrPop("doc", "$.tags"); // "typescript"
316
const lastScore = await client.json.arrPop("doc", "$.scores", -1); // "30"
317
318
// Trim array
319
await client.json.arrTrim("doc", "$.tags", 0, 2); // Keep first 3 elements
320
tags = await client.json.get("doc", { path: "$.tags" });
321
// ["redis", "database", "json"]
322
```
323
324
### Object Operations
325
326
JSON object manipulation operations.
327
328
```typescript { .api }
329
/**
330
* Get JSON object keys at path
331
* @param key - The JSON key
332
* @param path - JSON path (default: root '$')
333
* @returns Array of object keys, or array of key arrays for multiple paths
334
*/
335
function objKeys(key: RedisArgument, path?: string): Promise<ArrayReply<BlobStringReply> | ArrayReply<ArrayReply<BlobStringReply>>>;
336
337
/**
338
* Get number of keys in JSON object at path
339
* @param key - The JSON key
340
* @param path - JSON path (default: root '$')
341
* @returns Number of keys, or array of counts for multiple paths
342
*/
343
function objLen(key: RedisArgument, path?: string): Promise<NumberReply | ArrayReply<NumberReply | null>>;
344
```
345
346
**Usage Examples:**
347
348
```typescript
349
// Object operations
350
await client.json.set("user", "$", {
351
profile: {
352
name: "Alice",
353
age: 30,
354
email: "alice@example.com"
355
},
356
settings: {
357
theme: "dark",
358
notifications: true
359
}
360
});
361
362
// Get object keys
363
const profileKeys = await client.json.objKeys("user", "$.profile");
364
// ["name", "age", "email"]
365
366
const allKeys = await client.json.objKeys("user"); // Root object keys
367
// ["profile", "settings"]
368
369
// Get object length
370
const profileSize = await client.json.objLen("user", "$.profile"); // 3
371
const rootSize = await client.json.objLen("user"); // 2
372
```
373
374
### Utility Operations
375
376
Utility operations for JSON data management.
377
378
```typescript { .api }
379
/**
380
* Clear JSON value at path (set to default empty value)
381
* @param key - The JSON key
382
* @param path - JSON path (default: root '$')
383
* @returns Number of paths cleared
384
*/
385
function clear(key: RedisArgument, path?: string): Promise<NumberReply>;
386
387
/**
388
* Merge JSON value into existing JSON at path
389
* @param key - The JSON key
390
* @param path - JSON path
391
* @param value - JSON value to merge
392
* @returns 'OK'
393
*/
394
function merge(key: RedisArgument, path: string, value: RedisJSON): Promise<SimpleStringReply<'OK'>>;
395
396
/**
397
* Get memory usage of JSON value at path
398
* @param key - The JSON key
399
* @param path - JSON path (default: root '$')
400
* @returns Memory usage in bytes, or array of usage for multiple paths
401
*/
402
function debugMemory(key: RedisArgument, path?: string): Promise<NumberReply | ArrayReply<NumberReply>>;
403
```
404
405
**Usage Examples:**
406
407
```typescript
408
// Utility operations
409
await client.json.set("data", "$", {
410
counters: { a: 1, b: 2 },
411
items: ["x", "y", "z"],
412
config: { enabled: true }
413
});
414
415
// Clear array (makes it empty)
416
await client.json.clear("data", "$.items");
417
let items = await client.json.get("data", { path: "$.items" }); // []
418
419
// Clear object (makes it empty)
420
await client.json.clear("data", "$.counters");
421
let counters = await client.json.get("data", { path: "$.counters" }); // {}
422
423
// Merge objects
424
await client.json.merge("data", "$.config", { timeout: 5000, retries: 3 });
425
const config = await client.json.get("data", { path: "$.config" });
426
// { enabled: true, timeout: 5000, retries: 3 }
427
428
// Check memory usage
429
const memory = await client.json.debugMemory("data"); // Memory usage in bytes
430
const configMemory = await client.json.debugMemory("data", "$.config");
431
```
432
433
## JSON Path Syntax
434
435
RedisJSON uses JSONPath syntax for accessing JSON data:
436
437
```typescript
438
// JSONPath examples:
439
"$" // Root
440
"$.name" // Top-level 'name' field
441
"$.user.age" // Nested field access
442
"$.items[0]" // Array index access
443
"$.items[-1]" // Last array element
444
"$.items[*]" // All array elements
445
"$..name" // Recursive descent for 'name'
446
"$.items[?(@.active)]" // Filter expression
447
```
448
449
**Usage Examples:**
450
451
```typescript
452
await client.json.set("complex", "$", {
453
users: [
454
{ name: "Alice", age: 30, active: true },
455
{ name: "Bob", age: 25, active: false },
456
{ name: "Charlie", age: 35, active: true }
457
],
458
metadata: {
459
total: 3,
460
updated: "2023-01-01"
461
}
462
});
463
464
// Various path expressions
465
const firstUser = await client.json.get("complex", { path: "$.users[0]" });
466
const lastUser = await client.json.get("complex", { path: "$.users[-1]" });
467
const allNames = await client.json.get("complex", { path: "$.users[*].name" });
468
const activeUsers = await client.json.get("complex", { path: "$.users[?(@.active)]" });
469
```
470
471
## Type Conversion Helpers
472
473
```typescript { .api }
474
/**
475
* Transform JavaScript value to Redis argument
476
* @param json - JavaScript value
477
* @returns Redis argument representation
478
*/
479
function transformRedisJsonArgument(json: RedisJSON): RedisArgument;
480
481
/**
482
* Transform Redis reply to JavaScript value
483
* @param reply - Redis reply
484
* @returns JavaScript value
485
*/
486
function transformRedisJsonReply(reply: any): RedisJSON;
487
488
/**
489
* Transform Redis reply to JavaScript value with null handling
490
* @param reply - Redis reply
491
* @returns JavaScript value or null
492
*/
493
function transformRedisJsonNullReply(reply: any): RedisJSON | null;
494
```