Parsing JSON and REST APIs

Parsing JSON and REST APIs in PowerShell: Because PowerShell manipulates .NET objects, interacting with JSON Web APIs is seamless.

Because PowerShell manipulates .NET objects, interacting with JSON Web APIs is seamless. JSON is structurally identical to nested Hash Tables securely translating back and forth.

Parsing JSON

$jsonString = '{"user": "Admin", "id": 105, "roles": ["Read", "Write"]}'

# Convert string to a PowerShell custom object
$psObject = $jsonString | ConvertFrom-Json

Write-Output $psObject.user       # Admin
Write-Output $psObject.roles[1]   # Write

# Convert PowerShell Array/Object back into pure JSON text
$servers | ConvertTo-Json

Executing Web Requests

Invoke-RestMethod calls an endpoint and natively converts the returning JSON into a usable PowerShell object implicitly!

$githubApi = "https://api.github.com/users/microsoft/repos"

# Call the API. $repos is populated as a clean Array of Objects!
$repos = Invoke-RestMethod -Uri $githubApi -Method Get

# Instantly query the API result
$repos | Sort-Object stargazers_count -Descending | Select-Object -First 3 name, stargazers_count