Exploring JSON

JavaScript Object Notation (JSON) is a lightweight, text-based, open standard that is designed for data interchange. It is language-independent, with parsers available for Windows PowerShell.

The JSON format is often used to serialize and transmit structured data over a network connection. It is used primarily to transmit data between a server and a web application, as an alternative to XML.

You can use the following link to validate the JSON format:

http://jsonformatter.curiousconcept.com/

Here is a simple example of the JSON Format:

{
    "Title":  "Mr.",
    "Name":  "Scripting"
}

Windows PowerShell has two cmdlets: ConvertFrom-Json and ConvertTo-Json. Take a look at the following image:

Exploring JSON

As the name reads, it converts to and from. Let's take a look at how the following code works:

$json = @"
{
    "Title":  "Mr.",
    "Name":  "Scripting"
}
"@
$json | ConvertFrom-Json

Now, consider the following image:

Exploring JSON

The steps performed in the figure we just saw is explained as follows:

  • We have passed the JSON formatted code inside the here-string
  • Using pipeline we are converting the JSON to a PSCustomObject
  • Where Title and Name will be a NoteProperty with the values

Take a look at the following image:

Exploring JSON

Using JSON cmdlets, we can manipulate the contents as required:

$json = @"
{
    "User1": {"Name": "Chen", "Role": "SharePoint IT Pro"}, "User2": {"Name":"Keanu"}
}
"@
$data = $json | ConvertFrom-Json
$data.User1
$data.User2

Now, consider the following image:

Exploring JSON

It's easy to read a JSON file in PowerShell. Let's consider that we have a JSON file, as follows:

{
"1": "One",
"2": "Two",
"3": "Three"
} 
$data = Get-Content C:TempJSON.json -Raw | ConvertFrom-Json
$data.psobject.Properties.Name

The preceding code will provide the output as 1, 2, and 3.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset