我正在编写一个脚本来更改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)
这是由的自动字符转义功能引起的 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字符串的主题
另外,如果可能,请避免使用受影响的字符。
| 归档时间: |
|
| 查看次数: |
18300 次 |
| 最近记录: |