5

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?

ses
  • 13,174
  • 31
  • 123
  • 226

2 Answers2

18

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

randomir
  • 17,989
  • 1
  • 40
  • 55
  • thx. related in addition: https://stackoverflow.com/questions/47382769/vertx-config-redis-wrongtype-operation-against-a-key-holding-the-wrong-kind-of – ses Nov 19 '17 at 22:43
1

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
Itamar Haber
  • 47,336
  • 7
  • 91
  • 117
  • This doesn't work when `val` contains `\n` (try the OP's example). One option is to use `jq -c` to reformat the JSON file, but `-x` option of `redis-cli` can handle *any binary* data (including `NUL`s, which shell variables can never handle). – randomir Nov 18 '17 at 18:57
  • @randomir good point, and I do prefer your `-x` answer (I was the 1st upvote btw). However, the OP's core problem with the script was the lack of quotes so I felt compelled to point it out :) – Itamar Haber Nov 18 '17 at 21:28
  • 1
    Actually, I suggested quotes in the first draft of my answer (you can check the edits), but then realized they aren't reliable enough for handling custom JSON. :) BTW, nice work on `rejson` module! :) – randomir Nov 19 '17 at 12:53
  • thx. related in addition: https://stackoverflow.com/questions/47382769/vertx-config-redis-wrongtype-operation-against-a-key-holding-the-wrong-kind-of – ses Nov 19 '17 at 22:43