ConvertFrom-Json

PowerShell Cmdlet Deep Dive: ConvertFrom-Json

Welcome back to Wahmans Powershell blog! Today, we’re diving into an incredibly useful cmdlet: ConvertFrom-Json. It may sound simple—because it is—but don’t let its simplicity fool you. This little command can be a powerhouse when dealing with APIs, configuration files, and more.

What does ConvertFrom-Json do?

According to the Microsoft documentation:

Converts a JSON-formatted string to a custom object or a hash table.

Put a bit more simply: ConvertFrom-Json takes a JSON string and transforms it into a PowerShell object you can work with. This is perfect for when you’re calling APIs or dealing with configuration files written in JSON.

Let’s look at some examples, shall we?

Example 1: Basic JSON String to PSObject (Beginner)

$json = '{"name": "John", "age": 30, "city": "New York"}'
$user = $json | ConvertFrom-Json

# Accessing properties
$user.name  # Output: John
$user.age   # Output: 30

You can now work with $user just like any other PowerShell object. Simple, right?

Example 2: Parsing a JSON Array (Intermediate)

$json = '[
  {"name": "Alice", "age": 25},
  {"name": "Bob", "age": 28}
]'

$users = $json | ConvertFrom-Json

foreach ($user in $users) {
    Write-Output "$($user.name) is $($user.age) years old."
}
# Output:
# Alice is 25 years old.
# Bob is 28 years old.

This is incredibly convenient for parsing data returned from web APIs that deliver JSON arrays of items.

Example 3: Accessing Nested JSON (Advanced)

$json = '{
  "employee": {
    "name": "Jane",
    "contact": {
      "email": "[email protected]",
      "phone": "123-456-7890"
    }
  }
}'

$data = $json | ConvertFrom-Json

Write-Output $data.employee.name           # Output: Jane
Write-Output $data.employee.contact.email  # Output: [email protected]

Nested JSON? No problem! PowerShell effortlessly lets you traverse nested objects using dot notation.

Example 4: Parsing JSON from a REST API (Pro Tip)

$response = Invoke-RestMethod -Uri "https://jsonplaceholder.typicode.com/users"

# Convert to JSON string, then back to object (for demonstration purposes)
$jsonString = $response | ConvertTo-Json
$users = $jsonString | ConvertFrom-Json

foreach ($user in $users) {
    Write-Output "$($user.name) lives in $($user.address.city)"
}

Even if the Invoke-RestMethod already returns JSON converted to objects, sometimes you might grab raw JSON strings. That’s where ConvertFrom-Json comes in handy to transform it into structured PowerShell objects.

Wrapping Up

ConvertFrom-Json is a must-have tool for anyone working with data in PowerShell. Whether you’re a beginner parsing simple strings or a pro dealing with complex API responses, this cmdlet will make your life easier.

Happy scripting, and I will see you in the next post!

Leave a Reply

Your email address will not be published. Required fields are marked *