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

标签 json powershell

我正在编写用于更改JSON文件的脚本,但是当文件转换回JSON时,它将扩展特殊字符。

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

PS>“密码和123” |转换成杰森
输出为:“密码\ 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 FILE的示例
{
    "Server1":
    {
        "username":"root",
        "password":"Password&dfdf"
    },
    "Server2":
    {
        "username":"admin",
        "password":"Password&1234"
    }
}

最佳答案

这是由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}

如果您需要将密码不转义地存储,则可能需要进行一些更复杂的工作。看到关于Converting Unicode strings to escaped ascii strings的主题

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

关于json - PowerShell:包含特殊字符的ConvertTo-Json问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29306439/

相关文章:

arrays - 随机化 Powershell 数组中的元素列表

arrays - 在PowerShell中到数组的字符串(无定界符)

java - struts2-json-plugin JSONWriter 注入(inject)实战

sql - Postgres : push unique object into an array of jsonb

Python2 json : load using strings instead of unicode

javascript - 如何使用 Spotify Web API 制作音频播放器?

powershell - 如何确定命令输出对象?

python - Pandas 数据帧 : normalize one JSON column and merge with other columns

powershell - 使用 PowerShell 访问 Microsoft Graph

Powershell "special"开关参数