Need help with your JSON?
Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool
PowerShell: ConvertTo-Json and ConvertFrom-Json
PowerShell is a powerful automation and configuration management tool, and handling data in various formats is a common task. JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. PowerShell provides built-in cmdlets, ConvertTo-Json
and ConvertFrom-Json
, to seamlessly work with JSON data. These cmdlets are essential for tasks like interacting with web APIs, processing configuration files, or exchanging data between systems.
ConvertTo-Json: Exporting PowerShell Objects to JSON
The ConvertTo-Json
cmdlet converts a .NET object or a collection of objects into a JSON formatted string. This is incredibly useful when you have data in PowerShell (like variables, arrays, or output from other cmdlets) and need to send it as JSON, perhaps to a web service or save it to a file.
Basic Usage
You can pipe a PowerShell object directly to ConvertTo-Json
.
Example: Converting a Simple Object
$myObject = [PSCustomObject]@{ Name = "Alice" Age = 30 IsStudent = $false } $myObject | ConvertTo-Json
Output:
{ "Name": "Alice", "Age": 30, "IsStudent": false }
Converting Arrays/Collections
When you convert an array or a collection of objects, the cmdlet produces a JSON array.
Example: Converting an Array of Objects
$users = @( [PSCustomObject]@{ Name = "Alice"; Age = 30 }, [PSCustomObject]@{ Name = "Bob"; Age = 25 } ) $users | ConvertTo-Json
Output:
[ { "Name": "Alice", "Age": 30 }, { "Name": "Bob", "Age": 25 } ]
Handling Nested Objects with -Depth
By default, ConvertTo-Json
converts objects to a default depth of 2. If your object has nested properties that are themselves objects or arrays, you might need to increase the depth using the -Depth
parameter.
Example: Using -Depth
$data = @{ Site = "Example Website" Owner = @{ Name = "Admin" Contact = @{ Email = "admin@example.com" Phone = "555-1234" } } Categories = @("Web", "Tech", "JSON") } # Convert with default depth (2) - might truncate nested objects "$data | ConvertTo-Json # Often truncates deeply nested structures" # Convert with increased depth "$data | ConvertTo-Json -Depth 5 # Adjust depth based on your object structure"
Without sufficient depth, nested objects or arrays might appear as empty or incomplete in the JSON output. A common value is 100 or more for complex structures.
Formatting: Compressed vs. Expanded (Default)
By default, ConvertTo-Json
outputs human-readable JSON with indentation and line breaks. The -Compress
parameter removes whitespace, resulting in a single-line JSON string, which is useful for saving space or transmitting data.
Example: Using -Compress
$myObject = @{ ID = 1; Status = "Active" } # Default (Expanded) "$myObject | ConvertTo-Json" # Compressed "$myObject | ConvertTo-Json -Compress"
Output (Compressed):
{"ID":1,"Status":"Active"}
Handling Properties with -Force
Sometimes, objects might have properties that aren't typically enumerated or are hidden. The -Force
parameter can help include such properties in the JSON output.
Example: Using -Force (Conceptual)
# Some objects might have hidden properties # Get-Process | Select-Object -First 1 | ConvertTo-Json # Might miss some properties # Get-Process | Select-Object -First 1 | ConvertTo-Json -Force # Might include more # Use Select-Object explicitly for clarity and control over properties Get-ChildItem -Path $PSScriptRoot | Select-Object Name, Mode, Length | ConvertTo-Json
For predictable JSON output, it's often better to explicitly select the properties you want using Select-Object
before converting to JSON.
ConvertFrom-Json: Importing JSON into PowerShell Objects
The ConvertFrom-Json
cmdlet converts a JSON formatted string into a PowerShell object. This object is typically a PSCustomObject
or an array of PSCustomObject
s, making it easy to access the data using dot notation or array indexing, just like any other PowerShell object.
Basic Usage from a String
You can provide a JSON string as input, either directly or via a variable.
Example: Converting a JSON String to Object
$jsonString = '{ "FirstName": "Jane", "LastName": "Doe", "Age": 28, "IsEmployee": true }' $powerShellObject = $jsonString | ConvertFrom-Json # Accessing properties "$powerShellObject.FirstName" "$powerShellObject.Age"
Output:
Jane 28
Converting JSON Arrays
If the JSON string represents a JSON array, ConvertFrom-Json
returns an array of objects.
Example: Converting a JSON Array String
$jsonArrayString = '[ {"Name": "Apple", "Color": "Red"}, {"Name": "Banana", "Color": "Yellow"} ]' $powerShellArray = $jsonArrayString | ConvertFrom-Json # Accessing elements and properties "$powerShellArray[0].Name" "$powerShellArray[1].Color" "$powerShellArray | ForEach-Object { Write-Host "Fruit: $($_.Name), Color: $($_.Color)" }"
Output:
Apple Yellow Fruit: Apple, Color: Red Fruit: Banana, Color: Yellow
Reading JSON from Files
A common scenario is reading JSON data from a file. You can use Get-Content
to read the file's content and pipe it to ConvertFrom-Json
.
Example: Converting JSON from a File
# Assume you have a file named 'config.json' with JSON content # For example: {"Database": "MyDB", "Server": "SQL01"} "Get-Content -Path config.json | ConvertFrom-Json # Or for newer PowerShell versions (less common but possible): # ConvertFrom-Json -Path config.json # -Path parameter is less common/standard compared to piping Get-Content"
Ensure the file is encoded correctly (typically UTF-8) when reading it with Get-Content
. Use the -Encoding
parameter if needed.
Handling Malformed JSON
If the input string is not valid JSON, ConvertFrom-Json
will throw an error. You should include error handling (e.g., using try/catch
) if you are dealing with JSON from external or potentially unreliable sources.
Key Differences and Considerations
- Input/Output:
ConvertTo-Json
takes PowerShell objects and outputs a JSON string.ConvertFrom-Json
takes a JSON string (or string array) and outputs PowerShell objects. - Depth: Remember the default
-Depth 2
forConvertTo-Json
. This is a frequent source of truncated output for complex objects. - Object Types:
ConvertFrom-Json
createsPSCustomObject
s, which are very flexible. - Performance: For very large JSON files or strings, these cmdlets are generally efficient, but be mindful of memory usage when dealing with massive datasets.
Common Use Cases
- API Interactions:
- Use
ConvertTo-Json
to format the request body forInvoke-RestMethod
orInvoke-WebRequest
. - Use
ConvertFrom-Json
to parse the JSON response received from an API call into usable PowerShell objects.
- Use
- Configuration Files:
- Store application or script configurations in JSON files.
- Use
Get-Content | ConvertFrom-Json
to load configurations. - Use
ConvertTo-Json | Set-Content
to save configurations.
- Data Exchange:
- Export data from PowerShell into a JSON file for use by other applications (e.g., web frontends, other scripting languages).
- Import data from JSON files generated by other systems into PowerShell for processing or reporting.
Summary
ConvertTo-Json
and ConvertFrom-Json
are indispensable cmdlets for anyone working with JSON in PowerShell. They provide a straightforward way to translate data between PowerShell's object-oriented structure and the text-based JSON format, enabling integration with a wide range of tools and services that utilize JSON. Mastering these two commands opens up many possibilities for automation and data processing in your scripts.
Need help with your JSON?
Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool