Lea*_*Net 2 powershell json powershell-core powershell-7.0
我有以下 JSON,我想从 Address 下的 JSON 对象中删除街道,这是一个数组。我正在尝试在 powershell 中执行此操作
{
"Customer": [
{
"id": "123"
}
],
"Nationality": [
{
"name": "US",
"id": "456"
}
],
"address": [
{
"$type": "Home",
"name": "Houston",
"streets": [
{
"name": "Union",
"postalCode": "10",
}
]
},
{
"$type": "Office",
"name": "Hawai",
"streets": [
{
"name": "Rock",
"postalCode": "11",
}
]
}
],
"address": [
{
"$type": "Home1",
"name": "Houston",
"streets": [
{
"name": "Union1",
"postalCode": "14",
}
]
},
{
"$type": "Office1",
"name": "Hawaii1",
"streets": [
{
"name": "Rock1",
"postalCode": "15",
}
]
}
],
}
Run Code Online (Sandbox Code Playgroud)
我想从 JSON 对象中删除街道,这是我的 powershell 脚本,但它不起作用!我正在尝试将 JSON 转换为对象,然后循环遍历属性以删除它们。
$FileContent = Get-Content -Path "Test.json" -Raw | ConvertFrom-Json
foreach ($content in $FileContent) {
#Write-Host $content.address
$content.address = $content.address | Select-Object * -ExcludeProperty streets
}
$FileContent | ConvertTo-Json -Depth 100 | Out-File "Test.json" -Force
Run Code Online (Sandbox Code Playgroud)
当您使用ConvertFrom-Json它时,它会自动为您将事物转换为对象。一旦它们成为对象,您就可以使用它Select-Object来指定要包含在管道中的属性,您可以使用这些属性将$FileContent.address(对象数组)设置为等于自身,从数组中的每个对象中排除街道属性。
$FileContent = Get-Content -Path "Test.json" -Raw | ConvertFrom-Json
$FileContent.address = $FileContent.address | Select-Object * -ExcludeProperty streets
$FileContent | ConvertTo-Json
Run Code Online (Sandbox Code Playgroud)