Kjartan
Kjartan

Reputation: 19151

How to treat strings in ConvertFrom-Json as literals?

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?

Upvotes: 1

Views: 275

Answers (1)

zizizach
zizizach

Reputation: 26

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"
    }
}

Upvotes: 1

Related Questions