0

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

{ "value" : [{},{},{"name": "a"}] }
art-a-game
  • 123
  • 1
  • 1
  • 11

1 Answers1

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:

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • 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? – art-a-game Sep 21 '20 at 12:15
  • 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])` – Vasil Nikolov Sep 21 '20 at 12:57
  • @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. – mklement0 Sep 21 '20 at 12:59
  • @VasilSvilenovNikolov, modifying the `Where-Object` filter is enough; please see my previous comment. – mklement0 Sep 21 '20 at 13:01
  • Can this be done also recursively ? If let's say we have a PSObject lists that contain other object lists ? – Douda Aug 20 '23 at 17:35
  • 1
    @Douda, you'd have to use a recursive script block or function; see [this answer](https://stackoverflow.com/a/64189034/45375) for an example of recursively walking an object graph. If you have trouble adapting it to your needs, I suggest asking a new question. – mklement0 Aug 20 '23 at 21:49