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

24

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

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

PS> "Password&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"

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

{
    "Server1":
    {
        "username":"root",
        "password":"Password&dfdf"
    },
    "Server2":
    {
        "username":"admin",
        "password":"Password&1234"
    }
}
3个回答

50

尝试使用Unescape()方法:

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

12
警告:这会移除所有转义字符,包括一些在你的 JSON 中可能需要的字符,例如被转义的引号字符:"expression":"My name is "joe""。这将导致你的 JSON 数据变得不完整。 - Charlie Joynt
2
我发现以下答案最令人满意 - https://dev59.com/q1YN5IYBdhLWcg3wO14v#47779605 - Stringfellow

8
这是由于Convertto-Json的自动字符转义功能引起的,它会影响到多个符号,例如<>\'&。使用ConvertFrom-Json将正确读取转义字符。以您的示例为例:
PS C:\> {"Password\u0026123"} | ConvertFrom-Json
Password&123

你的示例代码生成了一个包含转义字符的文件,但 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}

如果需要存储未转义的密码,则可能需要进行更复杂的工作。请参阅有关将Unicode字符串转换为转义的ASCII字符串的主题。
或者,尽可能避免使用受影响的字符。

谢谢!我想我会着手处理一些将密码从JSON转换后再进行转换的工作... 一有进展就会更新... - Maki
我刚刚重新阅读了你的帖子,意识到这不再是一个真正的问题。现在看来只是一个表面问题。即使密码是Unicode格式,它也能正常工作。所以我暂时不会担心转换它。 - Maki

0

已使用 PowerShell 7.2 进行测试,似乎 Unicode 和其他特殊字符都能够成功转换。更不用说缩进也显得更加优化。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接