BudiBadu Logo
Samplebadu

PowerShell by Example: JSON

PowerShell 7

Converting between objects and JSON format with this sample code demonstrating ConvertTo-Json for serialization with depth control, ConvertFrom-Json for deserialization to PSCustomObject, property access on parsed JSON, and file-based JSON operations.

Code

# Create an object
$user = @{
    Name = "Alice"
    Roles = @("Admin", "User")
    Active = $true
}

# Convert to JSON string
$jsonString = $user | ConvertTo-Json -Depth 2
Write-Host $jsonString

# Parse JSON string back to object
$parsedObj = $jsonString | ConvertFrom-Json

# Access properties
Write-Host "Name: $($parsedObj.Name)"
Write-Host "First Role: $($parsedObj.Roles[0])"

# Reading from a JSON file
# $data = Get-Content config.json | ConvertFrom-Json

Explanation

PowerShell provides native JSON support through ConvertTo-Json and ConvertFrom-Json cmdlets. The ConvertTo-Json cmdlet serializes .NET objects including hashtables, arrays, and custom objects into JSON strings. The -Depth parameter controls serialization depth with a default of 2 levels, which may truncate deeply nested objects unless increased. The -Compress parameter removes whitespace for compact output.

The ConvertFrom-Json cmdlet deserializes JSON strings into PSCustomObject instances, allowing property access using standard dot notation. Arrays in JSON become PowerShell arrays, objects become PSCustomObjects, and primitive values map to corresponding .NET types. This automatic type conversion enables seamless interaction with JSON data from REST APIs, configuration files, and data interchange scenarios.

JSON operations are essential for modern DevOps workflows. The Invoke-RestMethod cmdlet automatically parses JSON responses from REST APIs, while Invoke-WebRequest requires manual parsing with ConvertFrom-Json. Configuration files in JSON format can be read using Get-Content piped to ConvertFrom-Json, and modified objects can be written back using ConvertTo-Json piped to Set-Content.

Code Breakdown

9
ConvertTo-Json -Depth 2 serializes object to JSON with depth limit.
13
ConvertFrom-Json deserializes JSON string to PSCustomObject.
16
Dot notation accesses properties on deserialized JSON object.
20
Get-Content piped to ConvertFrom-Json reads JSON files.