Master PowerShell ConvertTo-Json: Complete Guide with Examples

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.

Understanding ConvertTo-Json Basics

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"
}

Advanced Options and Parameters

ConvertTo-Json offers several parameters to customize the output format:

Depth Control

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

Compression

For API responses or large datasets, use Compress to reduce output size:

$data | ConvertTo-Json -Compress

Property Selection

Specify which properties to include using the Property parameter:

$user | ConvertTo-Json -Property Name, Email

Working with Collections

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"
}

Common Use Cases

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"

Handling Special Characters

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

Performance Considerations

For large datasets, consider these performance tips:

FAQ Section

Q: Why is ConvertTo-Json adding extra properties to my output?

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.

Q: Can I convert XML to JSON using PowerShell?

A: While ConvertTo-Json handles PowerShell objects, you'll need to parse XML first using [xml] or ConvertFrom-Xml, then convert the resulting object.

Q: How do I handle null values?

A: ConvertTo-Json represents null values as "null" in JSON output. Empty strings remain empty strings.

Q: What's the difference between ConvertTo-Json and ConvertFrom-Json?

A: ConvertTo-Json converts PowerShell objects to JSON strings, while ConvertFrom-Json does the reverse, parsing JSON into PowerShell objects.

Q: Can I customize the JSON property names?

A: Yes, use Select-Object with calculated properties to rename them before conversion, or use the Property parameter to select specific properties.

Best Practices

Follow these guidelines for optimal ConvertTo-Json usage:

  1. Always test with sample data before processing large datasets
  2. Use -Depth judiciously to balance completeness and performance
  3. Consider -Compress for API calls where readability isn't required
  4. Handle exceptions when converting potentially problematic objects
  5. Document your conversion requirements for team consistency

Troubleshooting Common Issues

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.

Conclusion

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.