将json值从文件设置为redis [英] set json value from file to redis
问题描述
我有一个bash.sh脚本:
I have a bash.sh script:
#!/usr/bin/env bash
val=$(cat ../my-microservice/conf/config.json)
echo "set my-microservice-config ${val}" | redis-cli
config.json:
where the config.json:
{
"key" : "value"
}
当我运行它时,我得到了:
When I run it I got:
ERR未知命令'}'
ERR unknown command '}'
如何从json文件中正确设置json值?
How to set a json value properly from the json file?
推荐答案
如果您要设置
If you are trying to set the 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
to read the last argument of the command verbatim, from stdin
. For example:
$ redis-cli -x set my-microservice-config < config.json
OK
以您的示例为例,它将存储:
For your example, this will store:
$ redis-cli get my-microservice-config
"{\n \"key\" : \"value\"\n}\n"
要存储JSON数据的紧凑表示形式,可以将 jq .
与
To store the compact representation of your JSON data, you can use jq .
with -c
flag:
$ jq -c . config.json | redis-cli -x set my-microservice-config
OK
$ redis-cli get my-microservice-config
"{\"key\":\"value\"}\n"
请注意,Redis本身不支持JSON,但是如果您需要,可以使用 ReJSON模块 解释的JSON值(JSON数据类型).
Note that Redis does not natively support JSON, but there's the ReJSON module you can use if you need interpreted JSON values (JSON datatype).
这篇关于将json值从文件设置为redis的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!