简体   繁体   中英

Remove Empty Object in JSON Array using powershell

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

{ "value" : [{},{},{"name": "a"}] }
# 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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM