gpt4 book ai didi

json 文件到 powershell 并返回到 json 文件

转载 作者:行者123 更新时间:2023-12-04 19:02:55 25 4
gpt4 key购买 nike

我正在尝试在 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

关于json 文件到 powershell 并返回到 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32959431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com