Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set json value from file to redis

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?

like image 249
ses Avatar asked Dec 04 '22 21:12

ses


2 Answers

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

like image 184
randomir Avatar answered Dec 06 '22 09:12

randomir


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
like image 24
Itamar Haber Avatar answered Dec 06 '22 09:12

Itamar Haber