ConvertFrom-Json – Unlock the Power of JSON in PowerShell
Welcome back to Wahmans PowerShell blog! Today, we’re diving into one of the most widely used and powerful cmdlets when working with JSON data in PowerShell – ConvertFrom-Json
. If you’ve ever had to parse JSON data from a web API or manipulate config files in JSON format, you’ll love what this cmdlet can do.
The Microsoft documentation puts it simply: “Converts a JSON-formatted string to a custom object.” Let’s break that down and look at four practical examples – each increasing in complexity – to help you master ConvertFrom-Json
.
🧰 Example 1: Basic JSON Parsing
Scenario: You have a simple JSON string and want to access its properties.
$json = '{"name": "Wahman", "language": "PowerShell"}'
$object = ConvertFrom-Json -InputObject $json
# Access properties
$object.name # Output: Wahman
$object.language # Output: PowerShell
This is the most basic use case and perfect when you’re starting with structured JSON data.
🔄 Example 2: Convert API JSON Response
Scenario: You’re calling an API and need to parse the JSON response.
$response = Invoke-RestMethod -Uri "https://jsonplaceholder.typicode.com/users/1" -Method Get
$jsonString = $response | ConvertTo-Json
$parsedObj = ConvertFrom-Json -InputObject $jsonString
Write-Output $parsedObj.name # Output: Leanne Graham
Write-Output $parsedObj.email # Output: [email protected]
This is great when using APIs like REST services. Even if Invoke-RestMethod
auto-converts JSON, this shows how you could handle raw strings.
📦 Example 3: Parsing JSON with Arrays
Scenario: JSON contains an array of objects (e.g., a list of users or items).
$json = '
[
{"id": 1, "name": "Alpha"},
{"id": 2, "name": "Bravo"},
{"id": 3, "name": "Charlie"}
]'
$array = ConvertFrom-Json -InputObject $json
foreach ($user in $array) {
Write-Output "User ID: $($user.id), Name: $($user.name)"
}
Using PowerShell’s support for arrays will allow you to quickly iterate and process each object.
⚙️ Example 4: Dealing with Nested JSON Objects
Scenario: JSON contains nested objects and you need to safely parse and navigate deep structures.
$json = @'
{
"user": {
"id": 42,
"profile": {
"username": "wahman42",
"preferences": {
"theme": "dark",
"notifications": true
}
}
}
}'@
$object = ConvertFrom-Json -InputObject $json
Write-Output $object.user.profile.username # Output: wahman42
Write-Output $object.user.profile.preferences.theme # Output: dark
Nesting can get complex, but PowerShell’s dot notation makes it easy to navigate.
🏁 Conclusion
ConvertFrom-Json
is an essential tool in your PowerShell skillset, particularly for cloud automation, third-party integrations, infrastructure-as-code (IaC), and managing configuration data. It enables you to go from raw JSON text to rich PowerShell objects with minimal effort.
Play around with these examples and start applying them in your scripts!
Happy scripting, and I will see you in the next post!
Leave a Reply to Monty Cancel reply