How to properly escape `string\\{{cfg}}` in json config file?


#1

I have an App that uses json for it’s connection config. I am attempting to build a string that contains multiple cfg’s from a binding. This is an example of my json:

{
  "Connection": "Server={{bind.database.first.sys.ip}}\\\\{{bind.database.first.cfg.instance}}"
}

When this is compiled into the config folder during hab svc load the file looks like this:

{
  "Connection": "Server=127.0.0.1\\{{bind.database.first.cfg.instance}}"
}

The ip is correctly replace and the \ is only two but for some reason the instance bind is not replaced. Also interesting is if I just put the string value of the instance then it will render all 4 backslashes. I am sure I am just doing something wrong but not sure how to get this to work.


#2

It looks like you need to replace your use of parentheses with handlebars

{{bind.database.first.cfg.instance}}


#3

Yeah sorry that was a typo in the forum post the json has handlebars in the correct places.


#4

I have found that backslashes in front of handlebars curly braces just does not work well. It is easier to address this if this were a script (like a hook) then you can do something like:

$inst = "{{bind.database.first.cfg.instance}}"
$connStr = "Server=127.0.0.1\$inst"

However in this case you are in a config file and don’t have the ability to assign variables. What I have done in these cases is have a hook manipulate the contents of the config file:

$inst = "{{bind.database.first.cfg.instance}}"
$connStr = "Server=127.0.0.1\$inst"

(Get-Content {{pkg.svc_config_path}}/Web.config).replace("%%conn%%", $connStr) | Set-Content www/Web.config

One thing to need to be careful about here is not to write to the config template. Notice that above I pull the original text from the config template, alter it and then write to another location. That is because if you were to write to the original config file, every configuration change in the ring would restart your service because it would result in a changed template where your replaced value would be restored to %%conn%%.