03 / FILES AND FORMATS · LESSON 12

Work with JSON configuration

Convert between JSON text and PowerShell objects.

12 min · learn at your pace

JSON is a text format

JSON describes objects, arrays, strings, numbers, Booleans, and null values. Use ConvertFrom-Json to turn JSON text into PowerShell data:

$config = Get-Content './config.json' -Raw | ConvertFrom-Json
$config.Name

-Raw reads the whole document as one string. That is useful for a structured document spread over multiple lines.

Make a targeted change

$config.RetryCount = 4
$config | ConvertTo-Json -Depth 10 | Set-Content './updated.json'

Convert back to JSON only after you have changed the object. The -Depth parameter controls how deeply nested objects are serialised. Choose a depth sufficient for your data and pay attention to truncation warnings.

The JSON in this lesson is a local fixture, not a live API response. The same conversion commands are useful when processing downloaded data on your own machine.

When editing configuration, preserve properties unrelated to your change. Reconstructing a whole document from only the field you care about can accidentally discard important settings.

Try an example.ps1
Get-Content './config.json' -Raw | ConvertFrom-Json
YOUR TURN

Put it into practice.

Update RetryCount from 2 to 4 in config.json. Save the full updated object to updated.json, preserving Name and Enabled.

See an explained solution
One way to solve it.ps1
$config = Get-Content './config.json' -Raw | ConvertFrom-Json
$config.RetryCount = 4
$config | ConvertTo-Json -Depth 10 | Set-Content './updated.json'

The script changes one property while retaining the rest of the configuration. RetryCount remains a JSON number.