PowerShell의 JSON 개체에서 특성 제거

Oct 01 2020

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

답변

5 TheMadTechnician Oct 01 2020 at 07:12

사용할 때 ConvertFrom-Json자동으로 사물을 개체로 변환합니다. 객체가되면 Select-Object파이프 라인에 포함 할 속성을 지정하는 데 사용할 수 있습니다. 이 속성을 사용 $FileContent.address하여 배열의 각 객체에서 streets 속성을 제외하고 자체적으로 동일하게 설정 (객체 배열) 할 수 있습니다 .

$FileContent = Get-Content -Path "Test.json" -Raw | ConvertFrom-Json
$FileContent.address = $FileContent.address | Select-Object * -ExcludeProperty streets
$FileContent | ConvertTo-Json