PowerShell – Working with JSON

email me

If you haven’t already done so, you’re eventually going to come across JSON files. JSON, or JavaScript Object Notation, is one of the most common file types for working with web APIs. On first glance, a JSON file can sometimes look like a mess, especially when dealing with large files (talking about you, Google preference file)—but, there is order to the chaos. In PowerShell, there are built-in cmdlets to handle the formatting. You can convert to and convert from JSON quite easily.

Here’s an example

$normalizedData = ""
$jsonData = ""
$data = ""

# data - this could be read from a text file
$data = [PSCustomObject] @{
FirstName = "Eddie";
LastName = "Jackson";
Zip = "12345";
Mobile = "111-222-3333";
}

# this will convert to json format
$jsonData = ConvertTo-Json $data


clear-host

Write-Host "[ Show Json Data ]`n"
$jsonData
Write-Host "`n`n"

# this will convert json format to powershell format
Write-Host "`n[ Show Normalized Data ]"
$normalizedData = ConvertFrom-Json $jsonData # | ft -HideTableHeaders
$normalizedData

$normalizedData = ""
$jsonData = ""
$data = ""

Output

 

Notes

ConvertTo-Json   ConvertFrom-Json  Invoke-WebRequest  Invoke-RestMethod 

Editing JSON with Visual Studio Code

Highlighter (Tomorrow Night Blue)