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
Building Your Crypto Portfolio the RIGHT Way!!|Building Your Crypto Portfolio the RIGHT Way!!
Lumen Technologies (NYSE:LUMN) Stock Forecast & Analyst Predictions - Simply Wall St
Jail Inquiry | Polk County Sheriff's Office
Tyler Sis 360 Louisiana Mo
Pickswise the Free Sports Handicapping Service 2023
Craigslist Vermillion South Dakota
Over70Dating Login
Seth Juszkiewicz Obituary
Myunlb
Louisiana Sportsman Classifieds Guns
Kitty Piggy Ssbbw
25Cc To Tbsp
How To Cancel Goodnotes Subscription
Earl David Worden Military Service
Kayky Fifa 22 Potential
I Saysopensesame
Zack Fairhurst Snapchat
Ge-Tracker Bond
Best Mechanics Near You - Brake Masters Auto Repair Shops
Robeson County Mugshots 2022
Food Universe Near Me Circular
Used Safari Condo Alto R1723 For Sale
Chime Ssi Payment 2023
Craigslist Panama City Beach Fl Pets
Tokyo Spa Memphis Reviews
Royalfh Obituaries Home
10-Day Weather Forecast for Santa Cruz, CA - The Weather Channel | weather.com
Ihs Hockey Systems
lol Did he score on me ?
Laveen Modern Dentistry And Orthodontics Laveen Village Az
Productos para el Cuidado del Cabello Después de un Alisado: Tips y Consejos
Utexas Baseball Schedule 2023
Bt33Nhn
No Hard Feelings Showtimes Near Tilton Square Theatre
#1 | Rottweiler Puppies For Sale In New York | Uptown
Gold Dipping Vat Terraria
Vocabulary Workshop Level B Unit 13 Choosing The Right Word
Lovely Nails Prices (2024) – Salon Rates
The Angel Next Door Spoils Me Rotten Gogoanime
2007 Jaguar XK Low Miles for sale - Palm Desert, CA - craigslist
Mathews Vertix Mod Chart
Promo Code Blackout Bingo 2023
✨ Flysheet for Alpha Wall Tent, Guy Ropes, D-Ring, Metal Runner & Stakes Included for Hunting, Family Camping & Outdoor Activities (12'x14', PE) — 🛍️ The Retail Market
Kate Spade Outlet Altoona
Ajpw Sugar Glider Worth
Craigslist Sparta Nj
Grand Park Baseball Tournaments
What Does the Death Card Mean in Tarot?
Tyrone Unblocked Games Bitlife
Dmv Kiosk Bakersfield
Coors Field Seats In The Shade
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.