将文件中的 json 值设置为 redis
set json value from file to redis
我有一个 bash.sh 脚本:
#!/usr/bin/env bash
val=$(cat ../my-microservice/conf/config.json)
echo "set my-microservice-config ${val}" | redis-cli
其中 config.json:
{
"key" : "value"
}
当我 运行 我得到了:
ERR unknown command '}'
如何从 json 文件正确设置 json 值?
如果您尝试将 string value of my-microservice-config
key to the contents of your JSON file (or any other for that matter, including binary), the simplest approach is to use the -x
option in redis-cli
设置为 ,请逐字阅读命令的最后一个参数 ,来自 stdin
。例如:
$ redis-cli -x set my-microservice-config < config.json
OK
对于您的示例,这将存储:
$ redis-cli get my-microservice-config
"{\n \"key\" : \"value\"\n}\n"
要存储 JSON 数据的紧凑表示,您可以使用 jq .
with -c
标志:
$ jq -c . config.json | redis-cli -x set my-microservice-config
OK
$ redis-cli get my-microservice-config
"{\"key\":\"value\"}\n"
请注意,Redis 本身不支持 JSON,但有 ReJSON module you can use if you need interpreted JSON values(JSON 数据类型)。
您需要在该值上使用引号,因为它包含空格 - 将脚本的最后一行更改为:
echo "set my-microservice-config \"${val}\"" | redis-cli
我有一个 bash.sh 脚本:
#!/usr/bin/env bash
val=$(cat ../my-microservice/conf/config.json)
echo "set my-microservice-config ${val}" | redis-cli
其中 config.json:
{
"key" : "value"
}
当我 运行 我得到了:
ERR unknown command '}'
如何从 json 文件正确设置 json 值?
如果您尝试将 string value of my-microservice-config
key to the contents of your JSON file (or any other for that matter, including binary), the simplest approach is to use the -x
option in redis-cli
设置为 ,请逐字阅读命令的最后一个参数 ,来自 stdin
。例如:
$ redis-cli -x set my-microservice-config < config.json
OK
对于您的示例,这将存储:
$ redis-cli get my-microservice-config
"{\n \"key\" : \"value\"\n}\n"
要存储 JSON 数据的紧凑表示,您可以使用 jq .
with -c
标志:
$ jq -c . config.json | redis-cli -x set my-microservice-config
OK
$ redis-cli get my-microservice-config
"{\"key\":\"value\"}\n"
请注意,Redis 本身不支持 JSON,但有 ReJSON module you can use if you need interpreted JSON values(JSON 数据类型)。
您需要在该值上使用引号,因为它包含空格 - 将脚本的最后一行更改为:
echo "set my-microservice-config \"${val}\"" | redis-cli