1

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?

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

Comments

0

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"

3 Comments

where type -eq 'type2' will produce the inverse of the result OP is asking for :)
yeah, I noticed this typo :) just after noticing you posted the same answer few minutes earlier :)
No problem, you can always edit your own posts

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.