Clean JSON output for ConvertTo-Json

PowerShell 5.1 has nice cmdlet called ConvertTo-Json that converts objects to JSON syntax. Unfortunately, this conversion isn’t very clean. It contains tons of extra white space and querying JSON is not possible for most of the tools including PowerShell.

PowerShell-Core 7 received a major update on cmdlet. It actually converts objects into clean JSON code.

I wrote a tiny function to demonstrate the different output between the two versions. The function shows memory in bytes and in GB after a small calculation. I added a second depth for demo purposes.

Function Get-MemoryArray {
    [array]$Memory = @('8192', '10240', '12288', '14336') #static array
    [array]$MemoryArray = @()
    Foreach ($Value in $Memory) {
        $Calc = $Value / 1024
        $MemoryArray += [PSCustomObject]@{
            Name  = "$Calc" + "GB"
            leveltwo = @{
                Value = $Value
    return $MemoryArray

Get-MemoryArray | ConvertTo-Json

PowerShell 5.1 generates the following output.

PowerShell-Core 7 returns a much cleaner output.

Clearly, it is recommended to use PowerShell-Core for JSON related scripts.