JSON operations let you easily change data between text and objects. This helps scripts talk with web services or save data in a simple format.
0
0
JSON operations (ConvertFrom-Json, ConvertTo-Json) in PowerShell
Introduction
When you get data from a web API and want to use it in your script.
When you want to save script data in a file that other programs can read.
When you need to send data from your script to another program or service.
When you want to read a JSON file and work with its data inside PowerShell.
When you want to convert PowerShell objects to JSON text for sharing or storage.
Syntax
PowerShell
ConvertFrom-Json [-InputObject] <string> [<CommonParameters>] ConvertTo-Json [-InputObject] <psobject> [-Depth <int>] [<CommonParameters>]
ConvertFrom-Json turns JSON text into PowerShell objects you can work with.
ConvertTo-Json turns PowerShell objects into JSON text you can save or send.
Examples
This converts JSON text to an object, then prints the name property.
PowerShell
$jsonText = '{"name":"Alice","age":30}'
$obj = $jsonText | ConvertFrom-Json
$obj.nameThis converts a PowerShell object to JSON text and prints it.
PowerShell
$obj = @{name='Bob'; age=25}
$jsonText = $obj | ConvertTo-Json
$jsonTextThis converts a JSON array to objects and prints the first item's name.
PowerShell
$jsonText = '[{"item":"apple","qty":5},{"item":"banana","qty":3}]' $list = $jsonText | ConvertFrom-Json $list[0].item
Sample Program
This script shows how to convert JSON text to an object, read and change data, then convert it back to JSON text.
PowerShell
$jsonString = '{"city":"Paris","temperature":18}' # Convert JSON text to object $weather = $jsonString | ConvertFrom-Json # Access properties Write-Output "City: $($weather.city)" Write-Output "Temperature: $($weather.temperature)°C" # Change temperature $weather.temperature = 20 # Convert back to JSON text $newJson = $weather | ConvertTo-Json Write-Output $newJson
OutputSuccess
Important Notes
Use the -Depth parameter with ConvertTo-Json if your object has nested objects deeper than 2 levels.
ConvertFrom-Json only works with valid JSON text. Invalid JSON will cause errors.
JSON keys become object properties you can access with dot notation.
Summary
ConvertFrom-Json changes JSON text into PowerShell objects.
ConvertTo-Json changes PowerShell objects into JSON text.
These commands help scripts work with data from web APIs or files easily.