我正在尝试在PowerShell中操作JSON文件数据并将其写回到文件中。甚至在进行操作之前,当我只是从文件中读取、在PowerShell中将其转换为Json对象并将其写回到文件中时,一些字符会被替换为一些代码。以下是我的代码:
$jsonFileData = Get-Content $jsonFileLocation
$jsonObject = $jsonFileData | ConvertFrom-Json
... (Modify jsonObject) # Commented out this code to write back the same object
$jsonFileDataToWrite = $jsonObject | ConvertTo-Json
$jsonFileDataToWrite | Out-File $jsonFileLocation
一些字符正在被替换为它们的代码。例如:
< is replaced by \u003c
> is replaced by \u003e.
' is replaced by \u0027
样例输入:
{
"$schema": "https://source.com/template.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"accountName": {
"type": "string",
"defaultValue": "<sampleAccountName>"
},
"accountType": {
"type": "string",
"defaultValue": "<sampleAccountType>"
},
},
"variables": {
"location": "sampleLocation",
"account": "[parameters('accountName')]",
"type": "[parameters('accountType')]",
}
}
输出:
{
"$schema": "https://source.com/template.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"accountName": {
"type": "string",
"defaultValue": "\u003csampleAccountName\u003e"
},
"accountType": {
"type": "string",
"defaultValue": "\u003csampleAccountType\u003e"
},
},
"variables": {
"location": "sampleLocation",
"account": "[parameters(\u0027accountName\u0027)]",
"type": "[parameters(\u0027accountType\u0027)]",
}
}
为什么会出现这种情况,我该如何做才能不替换字符并以相同方式写回它们?
application/json
,否则人们会期望ConvertTo-JSON
遵循JSON规范,该规范指定只有控制字符、双引号(U+0022)和相对较少的其他字符需要实际转义。任何其他字符都不需要。在PowerShell的GH上有一个未解决的问题,即当他们在PowerShell Core中切换到NewtonSoftJSON时,JSON与PSv5中的不同。简而言之,PS Core通过使用默认的NewtonSoft.Json字符串转义器来遵循JSON规范。 - fourpastmidnight