How to Convert String to JSON in PowerShell?

Recently, one of my clients asked me to convert a string to JSON for an automation script. I tried various methods in PowerShell. In this PowerShell tutorial, I will show you how to convert string to JSON in PowerShell using different methods.

To convert a string to JSON in PowerShell, the most common and straightforward method is using the ConvertTo-Json cmdlet. This cmdlet takes PowerShell objects as input and converts them into a JSON-formatted string. For example, you can create a hashtable with data about US cities and convert it to JSON like this: $cityData = @{ “New York” = @{ “Population” = 8336817 }; “Los Angeles” = @{ “Population” = 3898747 } }; $jsonString = $cityData | ConvertTo-Json.

Method 1: Using ConvertTo-Json Cmdlet

PowerShell provides the ConvertTo-Json cmdlet to convert PowerShell objects to JSON format. This method is very easy to use, and most PowerShell developers use it to work with JSON objects.

Here is an example.

$cityData = @{
    "New York" = @{
        "Population" = 8336817
        "State" = "New York"
    }
    "Los Angeles" = @{
        "Population" = 3898747
        "State" = "California"
    }
    "Chicago" = @{
        "Population" = 2746388
        "State" = "Illinois"
    }
}

$jsonString = $cityData | ConvertTo-Json
Write-Output $jsonString

This script creates a hashtable and then converts it to a JSON string.

I executed the above PowerShell script, and you can see it displays the JSON; look at the screenshot below:

Convert String to JSON in PowerShell

Read Convert String to Hashtable in PowerShell

Method 2: Using Here-Strings

Here is another method that you can use if the JSON structure is a little complex. You can use here-strings with a preformatted JSON, which allows for better readability:

You can see the screenshot below:

$jsonString = @"
{
    "NationalParks": [
        {
            "Name": "Yellowstone",
            "State": "Wyoming",
            "EstablishedYear": 1872
        },
        {
            "Name": "Yosemite",
            "State": "California",
            "EstablishedYear": 1890
        },
        {
            "Name": "Grand Canyon",
            "State": "Arizona",
            "EstablishedYear": 1919
        }
    ]
}
"@

$jsonObject = $jsonString | ConvertFrom-Json
Write-Output $jsonObject.NationalParks

This example creates a JSON string and then converts it to a PowerShell object for further manipulation.

Read Convert String to Int in PowerShell

Method 3: Using Custom Objects

You can also create custom PowerShell objects and convert them to JSON:

$usCapitals = @(
    [PSCustomObject]@{
        City = "Washington D.C."
        Type = "Federal Capital"
        Population = 689545
    },
    [PSCustomObject]@{
        City = "Albany"
        Type = "State Capital"
        State = "New York"
        Population = 96460
    },
    [PSCustomObject]@{
        City = "Sacramento"
        Type = "State Capital"
        State = "California"
        Population = 508529
    }
)

$jsonString = $usCapitals | ConvertTo-Json
Write-Output $jsonString

This script creates an array of custom objects and converts it to JSON.

Method 4: Handle Special Characters

When dealing with strings containing special characters, it’s important to ensure proper escaping. Here is a complete example and the script.

$cityDescription = @{
    "New Orleans" = "Known for its vibrant music scene & Mardi Gras"
    "San Francisco" = "Famous for the Golden Gate Bridge & cable cars"
    "Nashville" = "Home of country music & the \"Grand Ole Opry\""
}

$jsonString = $cityDescription | ConvertTo-Json -EscapeHandling EscapeNonAscii
Write-Output $jsonString

This example explains how to handle special characters and quotes in JSON conversion.

Here is also another example.

# Sample object with special characters
$data = @{
    Name = "Müller"
    City = "München"
    Description = "Café `"`"Zum schönen Müller`"`""
}

# Convert the object to JSON
$json = $data | ConvertTo-Json

# Output the JSON
$json

Check out How to Convert JSON to CSV in PowerShell?

Validate the JSON File

After converting a string to JSON, it’s essential to validate its correctness. PowerShell provides the Test-Json cmdlet for this purpose:

$jsonString = '{"Boston": {"Nickname": "The Hub", "State": "Massachusetts"}}'
$isValid = Test-Json $jsonString

if ($isValid) {
    Write-Output "The JSON is valid."
} else {
    Write-Output "The JSON is not valid."
}

This script checks if the generated JSON string is valid according to JSON standards.

You can see the output in the screenshot below:

PowerShell Convert String to JSON

Conclusion

In this tutorial, I have explained how to convert strings to JSON in PowerShell using different methods like:

  • Using ConvertTo-Json Cmdlet
  • Using Here-Strings
  • Using Custom Objects, etc.

I have also explained how to validate the JSON output by using the Test-Json PowerShell cmdlets.

You may also like the following tutorials:

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.