PowerShell developers frequently need to convert objects to JSON format for API interactions, configuration files, or data exchange. The ConvertTo-Json cmdlet is a powerful built-in tool that transforms PowerShell objects into properly formatted JSON strings. This guide covers everything you need to know about using ConvertTo-Json effectively in your automation workflows.
ConvertTo-Json is part of the standard PowerShell module and requires no additional installation. It accepts any PowerShell object as input and converts it to a JSON string representation. The cmdlet intelligently handles different object types, including simple objects, collections, and complex nested structures.
Here's a basic example of converting a simple PowerShell object to JSON:
$user = [PSCustomObject]@{
Name = "John Doe"
Age = 32
Email = "john@example.com"
}
$user | ConvertTo-Json
This produces clean JSON output with proper property names and values:
{
"Name": "John Doe",
"Age": 32,
"Email": "john@example.com"
}
ConvertTo-Json offers several parameters to customize the output format:
Use the Depth parameter to control how deep nested objects are converted. Default depth is 3, which works for most scenarios.
$complexObject | ConvertTo-Json -Depth 5
For API responses or large datasets, use Compress to reduce output size:
$data | ConvertTo-Json -Compress
Specify which properties to include using the Property parameter:
$user | ConvertTo-Json -Property Name, Email
When converting arrays or lists of objects, ConvertTo-Json automatically adds the @odata.context metadata. This is particularly useful for REST API responses.
$users = @(
[PSCustomObject]@{Name = "Alice"; Role = "Admin"},
[PSCustomObject]@{Name = "Bob"; Role = "User"}
)
$users | ConvertTo-Json
Output:
{
"Name": "Alice",
"Role": "Admin"
},
{
"Name": "Bob",
"Role": "User"
}
ConvertTo-Json shines in several real-world scenarios:
For example, when working with REST APIs, you might need to convert PowerShell objects to JSON before sending them:
$requestBody = [PSCustomObject]@{
title = "New Task"
completed = $false
userId = 1
}
$jsonBody = $requestBody | ConvertTo-Json -Compress
Invoke-RestMethod -Uri "https://api.example.com/tasks" -Method Post -Body $jsonBody -ContentType "application/json"
PowerShell's ConvertTo-Json automatically escapes special characters and Unicode. However, for complex objects with custom properties or methods, you might need additional processing.
Use the InputObject parameter with complex objects to ensure proper conversion:
$complexData = Get-Process | Select-Object -First 5 Name, Id, WorkingSet
$complexData | ConvertTo-Json -Depth 2
For large datasets, consider these performance tips:
A: ConvertTo-Json adds @odata.context for collections to provide metadata about the data structure. You can remove this by piping to Select-Object first.
A: While ConvertTo-Json handles PowerShell objects, you'll need to parse XML first using [xml] or ConvertFrom-Xml, then convert the resulting object.
A: ConvertTo-Json represents null values as "null" in JSON output. Empty strings remain empty strings.
A: ConvertTo-Json converts PowerShell objects to JSON strings, while ConvertFrom-Json does the reverse, parsing JSON into PowerShell objects.
A: Yes, use Select-Object with calculated properties to rename them before conversion, or use the Property parameter to select specific properties.
Follow these guidelines for optimal ConvertTo-Json usage:
Sometimes ConvertTo-Json might not behave as expected. Here are common problems and solutions:
Issue: Circular references
PowerShell objects with circular references can cause infinite loops. Use -Depth to limit recursion or break the circular reference before conversion.
Issue: Custom objects with methods
Methods and script blocks are automatically excluded from JSON output. Only data properties are included.
Issue: Large output files
For very large outputs, consider streaming to a file directly rather than holding the entire JSON string in memory.
PowerShell's ConvertTo-Json cmdlet is an essential tool for any PowerShell developer working with JSON data. Its flexibility and ease of use make it perfect for everything from simple object serialization to complex API interactions. By mastering the parameters and techniques outlined in this guide, you'll be able to handle JSON conversions efficiently in your automation workflows.
For those who frequently work with JSON formatting and need additional tools, check out our JSON Pretty Print tool for instant JSON formatting and validation. It's perfect for quickly checking your PowerShell JSON output or cleaning up malformed JSON strings from other sources.
Remember that JSON conversion is just one piece of the puzzle. Understanding how to work with JSON in PowerShell opens up countless automation possibilities, from API integration to data transformation and beyond.