JSON文件到PowerShell,并返回到JSON文件

问题描述:

我想操纵PowerShell中的JSON文件数据,并将其写回到文件。甚至在操作之前,当我刚刚从文件中读取时,将它转换为PowerShell中的Json对象并将其写回到文件中,某些字符正被一些代码所替代。以下是我的代码: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下的NET JavaScriptSerializer,问题或多或少已经回答here

下面是一些无耻copypaste:

的字符进行编码 “正确”!使用工作的JSON 库正确访问JSON数据 - 这是一个有效的JSON 编码。

转义这些字符可以防止通过JSON进行HTML注入 - 并且使得JSON XML友好的 。也就是说,即使JSON直接在JavaScript中被排除 (因为JSON是JavaScript的有效2子集),但它不能用于终止元素 ,因为相关字符(例如<,>)在JSON 本身内编码。


如果你真的需要把字符代码回到转义字符,最简单的方法可能是做一个正则表达式替换为每个字符代码。例如:

$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