How to Convert PowerShell Objects to JSON with ConvertTo-Json

Structured object data transforming into nested JSON for API requests and configuration files

What You’ll Learn

In this lesson, you’ll learn how to convert PowerShell objects into JSON using ConvertTo-Json. JSON is a text format commonly used by APIs, configuration files, and inventory tools.

  • Convert a custom PowerShell object into JSON.
  • Convert an array of objects into a JSON array.
  • Use the -Depth parameter for nested objects.
  • Save JSON to a file or prepare it for an API request.
Ad

The Concept

PowerShell works naturally with objects. For example, a system inventory record can contain properties such as a computer name, operating system, network information, and storage details.

JSON, however, is text. It represents data using property names, values, objects, and arrays. An API or configuration file can read this text even if it was created by PowerShell.

ConvertTo-Json serializes a PowerShell object. Serialization means turning an in-memory object into a format that can be stored or transmitted.

The basic syntax is:

$object | ConvertTo-Json

By default, PowerShell converts only a limited amount of nesting. If your object contains objects inside other objects, use -Depth to include those levels:

$object | ConvertTo-Json -Depth 3

The result is a string containing JSON. You can display it, save it with Set-Content, or pass it as the body of an HTTP request.

Basic Example

The following example creates a small system inventory record. The network and operating system values are nested objects, so the command uses -Depth 3.

$inventoryRecord = [pscustomobject]@{
    ComputerName = "APP-SERVER-01"
    OperatingSystem = [pscustomobject]@{
        Name = "Windows Server 2022"
        Version = "21H2"
    }
    Network = [pscustomobject]@{
        IPv4Address = "10.20.5.18"
        MacAddress = "00-15-5D-01-02-03"
    }
}

$inventoryRecord | ConvertTo-Json -Depth 3

Expected Output

{
    "ComputerName": "APP-SERVER-01",
    "OperatingSystem": {
        "Name": "Windows Server 2022",
        "Version": "21H2"
    },
    "Network": {
        "IPv4Address": "10.20.5.18",
        "MacAddress": "00-15-5D-01-02-03"
    }
}

How the Code Works

A flow diagram showing PowerShell inventory objects, including nested properties and arrays, being serialized by ConvertTo-Json with a suitable depth into JSON text, which is then saved to a file or prepared as an API request body.
PowerShell objects and arrays become JSON text through ConvertTo-Json; choose enough depth to preserve nested properties before saving or sending the result.

[pscustomobject]@{ ... } creates a custom PowerShell object. Each name before an equals sign becomes a property:

  • ComputerName is a simple string property.
  • OperatingSystem contains another custom object.
  • Network contains another custom object with two properties.

The pipe sends $inventoryRecord to ConvertTo-Json. The command reads the object’s properties and creates matching JSON property names and values.

-Depth 3 tells PowerShell how many nested levels to include. Without a sufficient depth, nested information may be incomplete or represented incorrectly. Use a depth large enough for your object, but avoid choosing an unnecessarily large value for very complex objects.

The output is JSON text, not another PowerShell object. This distinction matters when saving or sending the result: APIs and files generally need the serialized text.

Another Example

Real inventory usually contains more than one computer. An array of custom objects becomes a JSON array. This example also saves the serialized data to a file and prepares the same text as an API request body.

$inventory = @(
    [pscustomobject]@{
        ComputerName = "WEB-SERVER-01"
        Environment = "Production"
        Disks = @(
            [pscustomobject]@{
                Drive = "C:"
                SizeGB = 250
                FreeGB = 82
            }
        )
    },
    [pscustomobject]@{
        ComputerName = "WEB-SERVER-02"
        Environment = "Production"
        Disks = @(
            [pscustomobject]@{
                Drive = "C:"
                SizeGB = 250
                FreeGB = 116
            }
        )
    }
)

$jsonInventory = $inventory | ConvertTo-Json -Depth 4

$jsonInventory | Set-Content -Path ".\system-inventory.json" -Encoding utf8

$requestBody = $jsonInventory

$jsonInventory contains one JSON array with both computer records. Set-Content writes that text to system-inventory.json. The $requestBody variable is ready to use as the body of an HTTP request, for example with Invoke-RestMethod and an API’s actual URL.

When the file is used as a configuration file, you may also benefit from techniques for working with PowerShell configuration files.

Common Mistakes

Forgetting the depth of nested objects

The default depth may not be enough for an inventory record containing several levels of nested objects. If properties are missing or nested values do not look as expected, try a suitable value such as -Depth 3 or -Depth 4.

Converting the wrong value

Make sure you pipe the object or array you intend to serialize. For example, converting a display command’s formatted output can produce a different result than converting the original objects. Build or collect the objects first, then pipe those objects directly to ConvertTo-Json.

Confusing JSON text with a PowerShell object

After conversion, the result is text. You can save it or send it, but you cannot access its JSON properties as though it were still the original object. If you need to turn JSON text back into a PowerShell object, use ConvertFrom-Json.

Including sensitive information

Inventory data can expose hostnames, IP addresses, usernames, or other operational details. Review the properties before saving or sending JSON, and follow appropriate practices for protecting sensitive values.

Try It Yourself

Create a JSON record for a database server. Include its name, environment, operating system, and a nested storage object. Then convert it to JSON with a depth that includes all of the nested properties.

$databaseServer = [pscustomobject]@{
    ComputerName = "DB-SERVER-01"
    Environment = "Testing"
    OperatingSystem = [pscustomobject]@{
        Name = "Windows Server 2022"
        Version = "21H2"
    }
    Storage = [pscustomobject]@{
        Drive = "D:"
        SizeGB = 1000
        FreeGB = 640
    }
}

# Add your ConvertTo-Json command here

Challenge

Create an inventory array containing two server records:

  • Each record must include ComputerName and Role.
  • Each record must include a nested OperatingSystem object with Name and Version.
  • Convert the array to JSON with enough depth to include the nested operating system properties.
  • Save the result to server-inventory.json.

Solution

$servers = @(
    [pscustomobject]@{
        ComputerName = "API-SERVER-01"
        Role = "API"
        OperatingSystem = [pscustomobject]@{
            Name = "Ubuntu"
            Version = "22.04"
        }
    },
    [pscustomobject]@{
        ComputerName = "WORKER-SERVER-01"
        Role = "Worker"
        OperatingSystem = [pscustomobject]@{
            Name = "Windows Server 2022"
            Version = "21H2"
        }
    }
)

$serverJson = $servers | ConvertTo-Json -Depth 3
$serverJson | Set-Content -Path ".\server-inventory.json" -Encoding utf8

The $servers variable is an array because it contains multiple objects. Each object has a nested operating system object. ConvertTo-Json -Depth 3 preserves that nesting, and Set-Content writes the resulting JSON text to the requested file.

Key Takeaways

  • ConvertTo-Json serializes PowerShell objects and arrays into JSON text.
  • Nested objects may require the -Depth parameter.
  • An array of PowerShell objects becomes a JSON array.
  • Store the JSON in a variable before saving it or sending it to an API.
  • Review inventory data for sensitive information before sharing the JSON.

Leave a Comment

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

Scroll to Top
Ad
Ad
Ad