set json value from file to redis

 ̄綄美尐妖づ 提交于 2019-12-12 19:25:11

问题


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

where the config.json:

{
  "key" : "value"
}

When I run it I got:

ERR unknown command '}'

How to set a json value properly from the json file?


回答1:


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"

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"

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).




回答2:


You'll need to use quotes on the value as it contains spaces - change the last line of your script to:

echo "set my-microservice-config \"${val}\"" |  redis-cli


来源:https://stackoverflow.com/questions/47368364/set-json-value-from-file-to-redis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!