Eliminar un atributo del objeto JSON en powershell

Oct 01 2020

Tengo el siguiente JSON y me gustaría eliminar calles del objeto JSON en Dirección, que es una matriz. Estoy tratando de hacer esto en 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",
        }
      ]
    }
  ],
}

Me gustaría eliminar calles del objeto JSON y aquí está mi script de PowerShell, ¡pero no funciona! Estoy tratando de convertir JSON en un objeto y luego recorrer las propiedades para eliminarlas.

$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

Respuestas

5 TheMadTechnician Oct 01 2020 at 07:12

Cuando lo use ConvertFrom-Json, convertirá automáticamente las cosas en objetos para usted. Una vez que son objetos, puede usar Select-Objectpara especificar qué propiedades desea incluir en la canalización, con las que puede establecer $FileContent.address(una matriz de objetos) para que se igualen, excluyendo la propiedad de calles de cada objeto en la matriz.

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