PowerShell JSON
Preserve nested data deliberately and verify the properties after converting it back.
Documentation: Microsoft Learn
Overview
The configuration example contains strings, a number and a Targets array. JSON can represent that nested shape, whereas a flat CSV field needs an additional convention to store a list.
ConvertTo-Json has a serialization depth limit. Choose a depth that covers the schema you intend to exchange. Increasing it blindly can expose large or sensitive properties from operational objects, so build a small report object first.
For a JSON file, read the complete document with Get-Content -Raw before ConvertFrom-Json. Newline-delimited JSON is different: each line is its own document and needs its own conversion. An HTML error page from an API is not malformed application JSON; diagnose the response first.
Round-tripping through JSON does not preserve every .NET type or method. Verify values and structure that the receiving application needs rather than assuming that the original live object has been reconstructed.
Inspect this example’s structure
Read the command and its supplied arguments. This example requires real PowerShell or its module; this diagram does not execute it.
$config = [pscustomobject]@{
Environment = 'Production'
Retries = 3
Targets = @('WEB01' , 'WEB02') }
$config | ConvertTo-Json- Stage 1$config
Positional values or no named parameters - Stage 2ConvertTo-Json
Positional values or no named parameters
An example to inspect
Preview the example. Sign in for the full lesson and activities.
$config = [pscustomobject]@{
Environment = 'Production'
Retries = 3
Targets = @('WEB01' , 'WEB02') }
$config | ConvertTo-JsonWhat happens
The Targets value should remain an array containing WEB01 and WEB02. After conversion back, inspect Targets.Count and Retries. For deeper data, check a specific nested property as well as the top-level fields.
Worth remembering
A successful conversion is only the first check. Confirm the fields and nesting your consumer relies on.
Primary documentation
Try it
Illustrative output · values vary by environment
Example reader
Inspect this page's example
Run supported commands against the practice data, or inspect the example without executing it.
Ready to inspect.
Serialises an object containing an array to JSON.
Show reference output
Illustrative output · values vary by environment
{
"Environment": "Production",
"Retries": 3,
"Targets": [
"WEB01",
"WEB02"
]
}