2015-10-05 43 views
4

我想操縱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)]", 
    } 
} 

爲什麼會出現這種情況,我能做些什麼,使之不替換字符並寫回同樣的方式?

回答

5

由於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