ConvertTo-Json

The ConvertTo-Json command can be used to convert a PowerShell object (or hashtable) to JSON:

PS> Get-Process -Id $PID | 
    Select-Object Name, Id, Path | 
ConvertTo-Json 
 
{ 
    "Name":  "powershell_ise", 
    "Id":  3944, 
    "Path":  "C:\Windows\System32\WindowsPowerShell\v1.0\powershell_ise.exe" 
}  

By default, ConvertTo-Json will convert objects to a depth of two. Running the following code will show how the value for three is simplified as a string:

@{ 
one = @{    # 1st iteration 
two = @{    # 2nd iteration 
three = @{ 
four = 'value' 
            } 
        } 
    } 
} | ConvertTo-Json 

The property three is present, but the value is listed as System.Collections.Hashtable as acquiring the value would need a third iteration. Setting the value of the Depth parameter to three allows ConvertTo-Json to fully inspect the properties of three.

Going too deep:
JSON serialization is a recursive operation. The depth may be increased, which is useful when converting a complex object.
Some value types may cause ConvertTo-Json to apparently hang. This is caused by the complexity of those value types. Such value types may include circular references.
A ScriptBlock object, for example, cannot be effectively serialized as JSON. The following command takes over 15 seconds to complete and results in a string over 50 million characters long:
Measure-Command { { 'ScriptBlock' } | ConvertTo-Json -Depth 6 -Compress }
Increasing the recursion depth to 7 results in an error as keys (property names) begin to duplicate.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.22.164