set json value from file to redis

ses picture ses · Nov 18, 2017 · Viewed 7.1k times · Source

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?

Answer

randomir picture randomir · Nov 18, 2017

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