我有一个带有嵌套数组的 JSON,如下所示,要保存在 Redis 中。我正在使用 RedisJSON 模块将数据保存为 JSON。
customer:12345 : {
info : {
key1: val1,
key2: val2,
key3: val3
},
rides: [
{
rideid: xxx,
from: fromval,
to: toval,
date: dateofride,
distance: distanceval,
points: pointsval
},
{
rideid: yyy,
from: fromval,
to: toval,
date: dateofride,
distance: distanceval,
points: pointsval
},
...
]
}
我有一种情况,可以将新项目添加到数组中或可以编辑现有项目。我正在使用带有express.js的node-redis客户端。 Express 应用程序仅接收在行程数组中更改或添加的数据。如果该项目已在数组中,则新数据必须替换现有的数组项目(rideid 是每个对象的键),否则必须将其添加到数组中。我如何实现这一目标?
最佳答案
给定以下 JSON 文档
{
"info": {
"key1": "val1"
},
"rides": [{
"rideid": "xxx",
"points": 0
},
{
"rideid": "yyy",
"points": 10
}
]
}
由 RedisJSON 中的 key customer:12345
使用以下命令保存
127.0.0.1:6379> JSON.SET customer:12345 . "{\"info\": {\"key1\": \"val1\",\"key2\": \"val2\",\"key3\": \"val3\"},\"rides\":[{\"rideid\": \"xxx\",\"points\": 0 },\t{\"rideid\": \"yyy\",\"points\": 10}]}"
您可以使用rideid yyy
更新行程,例如将分数增加 5,如下
127.0.0.1:6379> JSON.NUMINCRBY customer:12345 "$.rides[?(@.rideid=='yyy')].points" 5
"[15]"
$.rides[?(@.rideid=='yyy')].points
是一个 JSONPath 表达式(更多 here 和 here ,还回答了 here )
添加新行程
127.0.0.1:6379> JSON.ARRAPPEND customer:12345 $.rides "{\"rideid\": \"zzz\",\"points\": 5 }"
1) (integer) 3
所有RedisJSON命令都可以在 here 找到
关于json - 操作 Redis JSON 中的嵌套对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70640933/