0

I have this JSON and I want to remove the empty object inside value array using powershell. Anyone can help?

{ "value" : [{},{},{"name": "a"}] }

1 Answer 1

3
# Parse the JSON into an object graph.
$obj = '{ "value" : [{},{},{"name": "a"}] }' | ConvertFrom-Json

# Filter out the empty objects, by counting the number of properties
# via the .psobject.Properties collection, available on any object in PowerShell.
# Note the need for @(...) to ensure that the result of the filtering remains
# an array.
$obj.Value = @($obj.Value | Where-Object { $_.psobject.Properties.Count -gt 0 })

# Reconvert to JSON.
$obj | ConvertTo-Json -Compress

The above yields:

{"value":[{"name":"a"}]}

See also:

Sign up to request clarification or add additional context in comments.

6 Comments

I have another question if its okay with you what if I will try to remove objects that has name which is equal to a?
For removal, you would need to use a .Remove() method on the $obj . Best way would probably be to re-cast the $obj in to a generic list $list=[System.Collections.Generic.List[System.Object]]::new() and then use the method $list.Remove($list[0])
@art-a-game, use Where-Object Name -ne 'a'; if you need to combine both criteria: Where-Object { $_.psobject.Properties.Count -gt 0 -and $_.Name -ne 'a' }. Use -cne instead of -ne for case-sensitive matching. If you have further questions, please create a new question post.
@VasilSvilenovNikolov, modifying the Where-Object filter is enough; please see my previous comment.
@Douda, you'd have to use a recursive script block or function; see this answer for an example of recursively walking an object graph. If you have trouble adapting it to your needs, I suggest asking a new question.
|

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.