How to Convert String to JSON in PowerShell? - PowerShell FAQs (2024)

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.

Table of Contents

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-JsonWrite-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:

How to Convert String to JSON in PowerShell? - PowerShell FAQs (1)

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-JsonWrite-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-JsonWrite-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 EscapeNonAsciiWrite-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 $jsonStringif ($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:

How to Convert String to JSON in PowerShell? - PowerShell FAQs (2)

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:

  • Convert String to Boolean in PowerShell
  • PowerShell IsNullOrEmpty() Example
  • How to Convert String to Double in PowerShell?

How to Convert String to JSON in PowerShell? - PowerShell FAQs (3)

Bijay Kumar

Bijay Kumar is an esteemed author and the mind behind PowerShellFAQs.com, where he shares his extensive knowledge and expertise in PowerShell, with a particular focus on SharePoint projects. Recognized for his contributions to the tech community, Bijay has been honored with the prestigious Microsoft MVP award. With over 15 years of experience in the software industry, he has a rich professional background, having worked with industry giants such as HP and TCS. His insights and guidance have made him a respected figure in the world of software development and administration. Read more.

How to Convert String to JSON in PowerShell? - PowerShell FAQs (2024)
Top Articles
Silent L—Explanation and Examples
Exactly How Long It Will Take For An Ex To Miss You
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Pearson Correlation Coefficient
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Greg O'Connell

Last Updated:

Views: 5815

Rating: 4.1 / 5 (42 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Greg O'Connell

Birthday: 1992-01-10

Address: Suite 517 2436 Jefferey Pass, Shanitaside, UT 27519

Phone: +2614651609714

Job: Education Developer

Hobby: Cooking, Gambling, Pottery, Shooting, Baseball, Singing, Snowboarding

Introduction: My name is Greg O'Connell, I am a delightful, colorful, talented, kind, lively, modern, tender person who loves writing and wants to share my knowledge and understanding with you.