2

我有以下 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",
        }
      ]
    }
  ],
}

我想从 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

4

1 回答 1

5

当您使用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
于 2020-10-01T00:12:51.697 回答