PowerShell JSON Format | How does the JSON type work in PowerShell? (2024)

PowerShell JSON Format | How does the JSON type work in PowerShell? (1)

Article byChirag Nagarekar

PowerShell JSON Format | How does the JSON type work in PowerShell? (2)

Reviewed byRavi Rathore

Updated March 4, 2023

PowerShell JSON Format | How does the JSON type work in PowerShell? (3)

Definition of PowerShell JSON Format

JSON format also stands for JavaScript Object Notation Format which is an Open Standard Format and in Human readable format and mainly used for faster communication between the browser and the client because its ease for processing and can be retrieved as PowerShell data using Web commands like Invoke-WebRequest and Invoke-RestMethod. Despite its name, this language is quite different than the JavaScript format.

ADVERTIsem*nT Popular Course in this categoryWINDOWS POWERSHELL - Specialization | 7 Course Series

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax:

JSON language uses the below syntax.

{
"String":"Value"
}

The above is the simple syntax of the JSON object format. It has the property header and the value and both are separated by the colon ( : ) which means that the particular header has that particular value.

JSON array Syntax,
{
"String":[
Value1,
Value2
]}

The above syntax shows that the String property header has two array values, Value1 and Value2.

Complex JSON structure,
{
"String":[
{
"String1":"Value1",
"String2":"Value2"
},
{
"String3":"Value3",
"String4":[
"Value4",
"Value5"
]}
]}

The above syntax shows the complex structure of the JSON format where it has a combination of the String and its values, arrays, and sub-strings and values.

How does the JSON type work in PowerShell?

JavaScript Object Notation or JSON files have the .json syntax. As we have seen in the above syntax section that the JSON is a String and a value pair and there are several such strings and values are associated with each other and it also comprises the array and subgroups of strings and values and can create a complex structure.

You can write a JSON file in any editor as it is a simple text format but to create an error-free JSON file, you can use the VS Code because it shows the error when there is any syntax missing. Second thing, once you are done with creating a JSON file, you can validate the JSON file online as well. Several websites validate the JSON file but https://jsonlint.com/ is the popular website to validate your JSON file.

PowerShell JSON Format | How does the JSON type work in PowerShell? (4)

Once the JSON file is created and validated, our task is to read the JSON file in PowerShell. PowerShell uses the two cmdlets ConvertTo-JSON and ConvertFrom-JSON to work with JSON files.

The ConvertTo-JSON cmdlet converts any possible output to the JSON format and the ConvertFrom-JSON cmdlet converts the JSON input to the custom Object or the hashtable format. First, we will check the sample input JSON file created above and how we can use the ConvertFrom-JSON command.

{
"Company":"AeroSpace",
"HeadOffice":"Russia",
"BranchOffices":[
"India",
"Australia"
]}

If you are directly working with the JSON file then you can use the below command to get the output into the hashtable format.

Get-Content .\Test1.json | ConvertFrom-Json

Output:

PowerShell JSON Format | How does the JSON type work in PowerShell? (5)

Or you can use the below command directly without saving the file as JSON.

$jsoninput='{
"Company":"AeroSpace",
"HeadOffice":"Russia",
"BranchOffices":[
"India",
"Australia"
]}'
$jsoninput|ConvertFrom-Json

Output:

PowerShell JSON Format | How does the JSON type work in PowerShell? (6)

To convert any output to the JSON format you need to use the ConvertTo-JSON command as shown below.

Get-Process notepad++ | Select Name, id, WorkingSet, CPU | ConvertTo-Json

Output:

PowerShell JSON Format | How does the JSON type work in PowerShell? (7)

In JSON structure, Boolean values $true and $false are defined as true or false respectively while $null is defined as null. See the example below.

Get-ChildItem -Path C:\Temp\25Aug2020.txt | ConvertTo-Json

Output:

PowerShell JSON Format | How does the JSON type work in PowerShell? (8)

You can see in the above output that null and true are defined and also the Date format is mentioned with /Date and the path is defined in a double backslash (“\\”) rather than a single backslash.

Examples

1. Converting Command output to the JSON file.

We can convert almost any command output to the JSON format using the ConvertTo-JSON pipeline command. For example,

Get-Process chrome | Select Name, ID, WorkingSet, CPU, PagedMemorySize64 | Select -First 3 | ConvertTo-Json

Output:

PowerShell JSON Format | How does the JSON type work in PowerShell? (9)

You can also compress the output using the -Compress parameter so that the output will be displayed in a single line as shown below.

Get-Process chrome | Select Name, ID, WorkingSet, CPU, PagedMemorySize64 | Select -First 3 | ConvertTo-Json -Compress

Output:

PowerShell JSON Format | How does the JSON type work in PowerShell? (10)

2. Converting JSON output to the array.

To convert the JSON output to the array, we need to use -AsArray parameter.

Please note: This parameter is only supported in the .Net Core versions (PowerShell 6.0 and above) but below 6.0 version (.Net Framework versions) it is not supported.

Without Converting to an array,

Get-Date | ConvertTo-Json

Output:

PowerShell JSON Format | How does the JSON type work in PowerShell? (11)

After converting to an array,

Get-Date | ConvertTo-Json -AsArray

Output:

PowerShell JSON Format | How does the JSON type work in PowerShell? (12)

There will be square brackets will be added when you convert JSON output to an array.

3. Using the Invoke-Webrequest

You can leverage JSON commands to work with the website output data. For example, we have a URL https://www.reddit.com/r/todayilearned/top.json?limit=100 which shows the Reddit top 100 posts from the particular page in a JSON format.

Invoke-WebRequest -Uri "https://www.reddit.com/r/todayilearned/top.json?limit=100" | ConvertFrom-Json

Output:

PowerShell JSON Format | How does the JSON type work in PowerShell? (13)

To read the titles of those posted contents,

$Out = Invoke-WebRequest -Uri "https://www.reddit.com/r/todayilearned/top.json?limit=100" | ConvertFrom-Json
$out.data.children.data | Select Title

Output:

PowerShell JSON Format | How does the JSON type work in PowerShell? (14)

The above command is similar to the RestAPI command which automatically formats the web JSON output data without using external ConvertFrom-JSON command.

Invoke-RestMethod -Uri "https://www.reddit.com/r/todayilearned/top.json?limit=100"

4. JSON commands to convert the output into HashTable

With the JSON commands, we can convert the output of the cmdlets directly to the hashtable as shown below.

Get-Service | ConvertTo-Json | ConvertFrom-Json

Output:

PowerShell JSON Format | How does the JSON type work in PowerShell? (15)

You can also select few fields,

Get-Service | Select Name, Starttype, Status | ConvertTo-Json | ConvertFrom-Json

Conclusion

JSON format has surpassed the use of the XML format because it is easier to deal with it and it is quicker to load for the browsers for the websites which use the heavy contents and this format is much lighter than the XML format. JSON files are also useful in the Infrastructure development automation by leveraging Infrastructure as a Code (IaaS) format and used by the cloud technologies as well mainly Azure to work with the Azure DevOps and ARM templates for deploying infrastructure resources as bulk and quickly.

Recommended Articles

This is a guide to PowerShell JSON Format. Here we discuss the definition, syntax, parameters, How does the JSON type work in PowerShell? and example with code implementation. You may also have a look at the following articles to learn more –

  1. PowerShell Invoke-Webrequest
  2. PowerShell Wait
  3. PowerShell Execution Policy
  4. PowerShell Sleep

ADVERTIsem*nT

MICROSOFT POWER BI - Specialization | 8 Course Series 34+ Hours of HD Videos 8 Courses Verifiable Certificate of Completion Lifetime Access4.5

ADVERTIsem*nT

ADVERTIsem*nT

MICROSOFT AZURE - Specialization | 15 Course Series | 12 Mock Tests 73 of HD Videos 15 Courses Verifiable Certificate of Completion Lifetime Access4.5

ADVERTIsem*nT

KALI LINUX - Specialization | 6 Course Series 20+ Hours of HD Videos 6 Courses Verifiable Certificate of Completion Lifetime Access4.5
Primary Sidebar

");jQuery('.cal-tbl table').unwrap("

");jQuery("#mobilenav").parent("p").css("margin","0");jQuery("#mobilenav .fa-bars").click(function() {jQuery('.navbar-tog-open-close').toggleClass("leftshift",7000);jQuery("#fix-bar").addClass("showfix-bar");/*jQuery(".content-sidebar-wrap").toggleClass("content-sidebar-wrap-bg");jQuery(".inline-pp-banner").toggleClass("inline-pp-banner-bg");jQuery(".entry-content img").toggleClass("img-op");*/jQuery("#fix-bar").toggle();jQuery(this).toggleClass('fa fa-close fa fa-bars');});jQuery("#mobilenav .fa-close").click(function() {jQuery('.navbar-tog-open-close').toggleClass("leftshift",7000);jQuery("#fix-bar").removeClass("showfix-bar");jQuery("#fix-bar").toggle();jQuery(this).toggleClass('fa fa-bars fa fa-close');/*jQuery(".content-sidebar-wrap").toggleClass("content-sidebar-wrap-bg");jQuery(".inline-pp-banner").toggleClass("inline-pp-banner-bg");jQuery(".entry-content img").toggleClass("img-op");*/});});

PowerShell JSON Format | How does the JSON type work in PowerShell? (2024)
Top Articles
Czym jest bitcoin
Acuity Insights | Casper
Nullreferenceexception 7 Days To Die
Katie Nickolaou Leaving
Genesis Parsippany
Gamevault Agent
Hk Jockey Club Result
Aries Auhsd
Youtube Combe
Find The Eagle Hunter High To The East
Keurig Refillable Pods Walmart
83600 Block Of 11Th Street East Palmdale Ca
Regal Stone Pokemon Gaia
Kaomoji Border
SXSW Film & TV Alumni Releases – July & August 2024
Average Salary in Philippines in 2024 - Timeular
Scotchlas Funeral Home Obituaries
97226 Zip Code
Cbssports Rankings
Between Friends Comic Strip Today
Vegito Clothes Xenoverse 2
Caring Hearts For Canines Aberdeen Nc
Pensacola Tattoo Studio 2 Reviews
Jurassic World Exhibition Discount Code
Things to do in Pearl City: Honolulu, HI Travel Guide by 10Best
Elijah Streams Videos
Ghid depunere declarație unică
Restaurants Near Calvary Cemetery
Giantess Feet Deviantart
Magicseaweed Capitola
Craigslist Pets Huntsville Alabama
The disadvantages of patient portals
Is The Nun Based On a True Story?
Review: T-Mobile's Unlimited 4G voor Thuis | Consumentenbond
11301 Lakeline Blvd Parkline Plaza Ctr Ste 150
Bcy Testing Solution Columbia Sc
Walmart Pharmacy Hours: What Time Does The Pharmacy Open and Close?
All Obituaries | Sneath Strilchuk Funeral Services | Funeral Home Roblin Dauphin Ste Rose McCreary MB
Citroen | Skąd pobrać program do lexia diagbox?
Comanche Or Crow Crossword Clue
10 Types of Funeral Services, Ceremonies, and Events » US Urns Online
The Average Amount of Calories in a Poke Bowl | Grubby's Poke
Race Deepwoken
Naomi Soraya Zelda
Diesel Technician/Mechanic III - Entry Level - transportation - job employment - craigslist
Where Is Darla-Jean Stanton Now
Grandma's Portuguese Sweet Bread Recipe Made from Scratch
28 Mm Zwart Spaanplaat Gemelamineerd (U999 ST9 Matte | RAL9005) Op Maat | Zagen Op Mm + ABS Kantenband
Minecraft Enchantment Calculator - calculattor.com
Invitation Quinceanera Espanol
Olay Holiday Gift Rebate.com
Latest Posts
Article information

Author: Madonna Wisozk

Last Updated:

Views: 5970

Rating: 4.8 / 5 (68 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Madonna Wisozk

Birthday: 2001-02-23

Address: 656 Gerhold Summit, Sidneyberg, FL 78179-2512

Phone: +6742282696652

Job: Customer Banking Liaison

Hobby: Flower arranging, Yo-yoing, Tai chi, Rowing, Macrame, Urban exploration, Knife making

Introduction: My name is Madonna Wisozk, I am a attractive, healthy, thoughtful, faithful, open, vivacious, zany person who loves writing and wants to share my knowledge and understanding with you.