Json 文件到 powershell 并返回 json 文件

Json file to powershell and back to json file

我正在尝试在 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)]",
    }
}

为什么会这样,我该怎么做才能不替换字符并以相同的方式写回它们?

由于 ConvertTo-Json 在后台使用 .NET JavaScriptSerializer,问题或多或少已经得到解答 here

这是一些无耻的复制粘贴:

The characters are being encoded "properly"! Use a working JSON library to correctly access the JSON data - it is a valid JSON encoding.

Escaping these characters prevents HTML injection via JSON - and makes the JSON XML-friendly. That is, even if the JSON is emited directly into JavaScript (as is done fairly often as JSON is a valid2 subset of JavaScript), it cannot be used to terminate the element early because the relevant characters (e.g. <, >) are encoded within JSON itself.


如果您真的需要将字符代码转换回非转义字符,最简单的方法可能是对每个字符代码进行正则表达式替换。示例:

$dReplacements = @{
    "\u003c" = "<"
    "\u003e" = ">"
    "\u0027" = "'"
}

$sInFile = "infile.json"
$sOutFile = "outfile.json"

$sRawJson = Get-Content -Path $sInFile | Out-String
foreach ($oEnumerator in $dReplacements.GetEnumerator()) {
    $sRawJson = $sRawJson -replace $oEnumerator.Key, $oEnumerator.Value
}

$sRawJson | Out-File -FilePath $sOutFile