1

I'm importing a set of configuration values from a file in JSON format using the following:

$configFileContent = Get-Content -Path run.config | ConvertFrom-Json

This produces a result that among other things, contains the following (the contents of the variable $configFileContent):

{
    "config-values":{
        "path":"..\temp-path"
    }
}

Next, I try to access the value of path from that config as follows:

$conf = $configFileContent.'config-values'
$tempPath = $conf.'path'

..but this fails due to the characters \t in ..\temp-path being interpreted as an escape sequence representing a Tab instead. This is clear by printing the contents of $conf, which is now:

path
----
..      emp-path

As you can see, the value of Path is .. <tab> emp-path instead of ..\temp-path, as intended. Obviously this causes trouble later when I'm trying to use the variable $tempPath as an actual path.

How can I make Powershell interpret this as intended - i.e., treat strings as literals here?

Kjartan
  • 18,591
  • 15
  • 71
  • 96
  • It's the JSON parser that does this. Backslashes in JSON need to be escaped (`"path":"..\\temp-path"`). [Related](https://stackoverflow.com/q/32056940/1630171). Essentially you need to fix your input data. – Ansgar Wiechers Oct 04 '19 at 07:41

1 Answers1

1

I understand this may not be the answer you are looking for. But the quick fix is to use a double backslash in your JSON file

It is also a common workaround in all other languages

{
    "config-values":{
        "path":"..\\temp-path"
    }
}
Didier Aupest
  • 3,227
  • 2
  • 23
  • 35
zizizach
  • 26
  • 2
  • I see, and this makes sense. I guess I didn't consider that it could be an actual property of the JSON language, but it clearly is. Thanks for your input. – Kjartan Oct 04 '19 at 10:07