PowerShell:ConvertTo-Json包含特殊字符的问题

Mak*_*aki 14 powershell json

我正在编写一个脚本来更改JSON文件,但是当文件转换回JSON时,它会扩展特殊字符.

例如,JSON文件包含带有"&"的密码.复制问题的快速方法是使用以下命令:

PS>"密码&123"| Convertto-Json输出为:"Password\u0026123"

##Here is how I import the JSON FILE:
$jsonfile = (Get-Content .\example.json -Encoding Ascii) -join "`n" | ConvertFrom-Json
##Exporting JSON FILE without modifying it.
$jsonfile  | ConvertTo-Json |Out-File "new.json"
Run Code Online (Sandbox Code Playgroud)

- 这是一个简化的JSON文件的例子

{
    "Server1":
    {
        "username":"root",
        "password":"Password&dfdf"
    },
    "Server2":
    {
        "username":"admin",
        "password":"Password&1234"
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 25

尝试使用Unescape()方法:

$jsonfile | ConvertTo-Json | % { [System.Text.RegularExpressions.Regex]::Unescape($_) } | Out-File "new.json"
Run Code Online (Sandbox Code Playgroud)

  • 警告:这将删除所有转义,包括JSON中可能需要的转义,例如转义引号字符:`"expression":"我的名字是\"joe \""`.这会让你失去JSON ...... (7认同)
  • 我发现以下答案最令人满意 - /sf/answers/3344572381/ (2认同)

Boo*_*Roo 5

这是由的自动字符转义功能引起的 Convertto-Json并且会影响多个符号,例如<>\'&

ConvertFrom-Json将正确读取转义的字符。使用您的示例:

PS C:\> {"Password\u0026123"} | ConvertFrom-Json
Password&123
Run Code Online (Sandbox Code Playgroud)

您的示例代码将导致文件中的字符转义,但ConvertFrom-Json可以将其读回原始密码。见下文:

PS C:\> (Get-Content .\example.json -Encoding Ascii) -join "`n" | ConvertFrom-Json
Server1                                  Server2
-------                                  -------
@{username=root; password=Password&dfdf} @{username=admin; password=Password&1234}

PS C:\> (Get-Content .\new.json -Encoding Ascii) -join "`n" | ConvertFrom-Json
Server1                                  Server2
-------                                  -------
@{username=root; password=Password&dfdf} @{username=admin; password=Password&1234}
Run Code Online (Sandbox Code Playgroud)

如果您需要将密码不转义地存储,则可能需要进行一些更复杂的工作。请参阅有关将Unicode字符串转换为转义的ascii字符串的主题

另外,如果可能,请避免使用受影响的字符。