Remove an attribute from the JSON object in powershell

6.4k views Asked by At

I have following JSON and I would like to remove streets from the JSON object under Address which is an array. I am trying to do this in 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",
        }
      ]
    }
  ],
}

I would like to remove streets from the JSON object and here is my powershell script but it is not working! I am trying to convert JSON into object and then loop over properties to remove those.

$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

1

There are 1 answers

5
TheMadTechnician On BEST ANSWER

When you use ConvertFrom-Json it will automatically convert things to objects for you. Once they're objects you can use Select-Object to specify what properties you want to include in the pipeline, with which you can just set $FileContent.address (an array of objects) to equal itself, excluding the streets property from each object in the array.

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