在 Redis 中将 JSON 存储为字符串时转义特殊字符

Escaping special characters while storing JSON as string in Redis

我正在尝试通过 PHP 在 Redis 中存储 JSON 数据,但通过 redis-cli 命令行客户端对其进行测试。

在两个客户端中,我似乎无法存储 JSON 而不以某种方式转义它。

redis 127.0.0.1:6379> set test1 {"array":[1,2,3],"number":123,"object":{"a":"b","c":"d","e":"f"},"string":"Hello World"}
Invalid argument(s)

无效。

redis 127.0.0.1:6379> set test1 '{"array":[1,2,3],"number":123,"object":{"a":"b","c":"d","e":"f"},"string":"Hello World"}'
Invalid argument(s)

试过单引号。不起作用。

redis 127.0.0.1:6379> set test1 \{\"array\"\:\[1\,2\,3\]\,\"number\"\:123\,\"object\"\:\{\"a\"\:\"b\"\,\"c\"\:\"d\"\,\"e\"\:\"f\"\},\"string\"\:\"Hello World\"\}
Invalid argument(s)

尝试用反斜杠转义所有内容。不起作用。

redis 127.0.0.1:6379> "\{\"array\"\:\[1\,2\,3\]\,\"number\"\:123\,\"object\"\:\{\"a\"\:\"b\"\,\"c\"\:\"d\"\,\"e\"\:\"f\"\},\"string\"\:\"Hello World\"\}"
OK

尝试使用反斜杠和双引号转义所有内容。

而且有效!

redis 127.0.0.1:6379> get test1
"{\"array\":[1,2,3],\"number\":123,\"object\":{\"a\":\"b\",\"c\":\"d\",\"e\":\"f\"},\"string\":\"Hello World\"}"

现在在 serialize() 或 json_encode() 中有一个简单的参数,它允许自动发生,

我必须使用 preg_replace() 编写一个自定义函数,以便在存储时添加斜线,然后在检索时删除斜线,并希望没有特定的棘手数据会破坏我基于正则表达式的自定义代码。

如果有合适的方法的话,我觉得第二种方案确实不可取

知道这样的选项是什么吗?

我无法使用 Predis(我试过 https://github.com/nrk/predis/tree/php5.2_backport because I am working on PHP 5.2) but then found https://github.com/joelcox/codeigniter-redis 它完美地适用于所有基本数据类型。

那么,serialize() / json_encode() 的选项/参数是什么,它将允许 redis-cli 不会拒绝的字符串?

嗯,结果是第 118 行 https://github.com/joelcox/codeigniter-redis/blob/develop/libraries/Redis.php

public function command($string)
{
    $slices = explode(' ', $string); /* <-- HERE  */
    $request = $this->_encode_request($slices[0], array_slice($slices, 1));
    return $this->_write_request($request);
}

盲目地用 space 字符分割整个命令。

因为我的数据中有 spaces(现实世界的数据没有...),这破坏了 Redis CLI 语法。

所以我不得不转义 spaces(替换为自定义字符串)以使其正常工作。