Home > Enterprise >  Remove Object from Array of Objects in Json/powershell
Remove Object from Array of Objects in Json/powershell

Time:02-18

I am importing JSON into Powershell to replace some values, but I also need to remove some objects from there.

Import:

$fileJson = Get-Content -path/Template.json  -Encoding UTF8

I have an array of object which looks like this:

{
 "resources": [
   {
     "name": "name1"
     "type": "type1"
     "....": "....."
   }, 
   {
     "name": "name2"
     "type": "type2"
     "....": "....."
   },
   {
     "name": "name3"
     "type": "type1"
     "....": "....."
   }
 ]
}

and I want to remove a specific object from this array of objects. For example I want to remove Object where "type" equals "type2".

I have already tried to replace values with .Replace, however I can only replace single values and not the complete object.

Is it possible to delete or skip entire object with condition?

CodePudding user response:

Convert the JSON to a custom object:

$fileJson = Get-Content -path/Template.json  -Encoding UTF8
$data = $fileJson |ConvertFrom-Json 

Use Where-Object to filter the resources array:

$data.resources = @($data.resources |Where-Object type -ne type2)

Convert the now modified object back to JSON and write to disk:

$data |ConvertTo-Json |Set-Content ./path/to/updatedTemplate.json -Encoding UTF8

CodePudding user response:

I suggest to convert json into PowerShell objects, then make desired changes. then convert back to json if needed.

Example

$root = Get-Content -Path "C:\source.json" | ConvertFrom-Json
$root.resources = $root.resources | where type -eq 'type2'
$root | ConvertTo-Json -Depth 5 | Out-File "C:\destination.json"
  • Related