PowerShell:包含特殊字符的 ConvertTo-Json 问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29306439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PowerShell: ConvertTo-Json problem containing special characters
提问by Maki
I am writing a script to make changes to a JSON file but when the file is converted back to JSON it expands special characters.
我正在编写一个脚本来更改 JSON 文件,但是当文件转换回 JSON 时,它会扩展特殊字符。
For example the JSON File contain passwords with "&". A quick way to replicate the problem is using following command:
例如,JSON 文件包含带有“&”的密码。复制问题的快速方法是使用以下命令:
PS> "Password&123" | Convertto-Json output is:"Password\u0026123"
PS> "密码&123" | Convertto-Json 输出为:“密码\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"
--here is an example of simplified JSON FILE
--这里是一个简化的JSON文件的例子
{
"Server1":
{
"username":"root",
"password":"Password&dfdf"
},
"Server2":
{
"username":"admin",
"password":"Password&1234"
}
}
采纳答案by Booga Roo
This is caused by the automatic character escape feature of Convertto-Jsonand it affects several symbols such as <>\'&
这是由 的自动字符转义功能引起的Convertto-Json,它会影响几个符号,例如<>\'&
ConvertFrom-Json will read the escaped characters properly. Using your example:
ConvertFrom-Json 将正确读取转义字符。使用您的示例:
PS C:\> {"Password\u0026123"} | ConvertFrom-Json
Password&123
And your example code results in a file that has escaped characters, but ConvertFrom-Jsoncan read it back to the original passwords. See below:
并且您的示例代码会生成一个包含转义字符的文件,但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}
If you need the passwords to be stored unescaped, some fancier work may be needed. See this thread about Converting Unicode strings to escaped ascii strings
如果您需要不转义地存储密码,则可能需要一些更有趣的工作。请参阅有关将 Unicode 字符串转换为转义的 ascii 字符串的线程
Alternatively, avoid affected characters if possible.
或者,尽可能避免受影响的字符。
回答by Vladimir Dronov
Try the Unescape() method:
试试 Unescape() 方法:
$jsonfile | ConvertTo-Json | % { [System.Text.RegularExpressions.Regex]::Unescape($_) } | Out-File "new.json"

