我將 JSON 匯入 Powershell 以替換一些值,但我還需要從那里洗掉一些物件。
進口:
$fileJson = Get-Content -path/Template.json -Encoding UTF8
我有一個物件陣列,如下所示:
{
"resources": [
{
"name": "name1"
"type": "type1"
"....": "....."
},
{
"name": "name2"
"type": "type2"
"....": "....."
},
{
"name": "name3"
"type": "type1"
"....": "....."
}
]
}
我想從這個物件陣列中洗掉一個特定的物件。例如,我想洗掉"type" 等于 "type2"的物件。
我已經嘗試用 .Replace 替換值,但是我只能替換單個值而不是完整的物件。
是否可以洗掉或跳過有條件的整個物件?
uj5u.com熱心網友回復:
將 JSON 轉換為自定義物件:
$fileJson = Get-Content -path/Template.json -Encoding UTF8
$data = $fileJson |ConvertFrom-Json
用于Where-Object過濾resources陣列:
$data.resources = @($data.resources |Where-Object type -ne type2)
將現在修改的物件轉換回 JSON 并寫入磁盤:
$data |ConvertTo-Json |Set-Content ./path/to/updatedTemplate.json -Encoding UTF8
uj5u.com熱心網友回復:
我建議將 json 轉換為 PowerShell 物件,然后進行所需的更改。然后在需要時轉換回 json。
例子
$root = Get-Content -Path "C:\source.json" | ConvertFrom-Json
$root.resources = $root.resources | where type -eq 'type2'
$root | ConvertTo-Json -Depth 5 | Out-File "C:\destination.json"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/426807.html
