Explain JSON format in PowerShell.


Javascript Object Notation (JSON) is the light-weight structure which is easy to read by human and simple to parse and understand by machine. Although the name contains the Javascript, both Javascript and JSON are different and they have syntax and structure is different as well.

You can get more information about JSON

https://www.json.org/json-en.html

Its basic structure is Key-Value pair but both are separated by a colon ‘:’. It has an almost similar structure as a hashtable, PSCustomObjecct. For example,

{
   "Name": "Albert Don"
}

If you have multiple Key-Value pairs, you can separate them with a comma. For example,

{
   "Name": "Albert Don",
   "City": "New York",
   "SSID": 17728839
}

Save the above file with the extension .json. We will first use the ConvertFrom-Json command to get the output in the table format. There is another command to convert the file/output into JSON using ConvertTo-Json command.

PS E:\scripts\Powershell> Get-Content .\test.json | ConvertFrom-Json
Name          City       SSID
----          ----       ----
Albert Don    New York 17728839

If you have more than one set of Key-Value pairs then you need to declare them inside array Syntax - [] and need to separate each set with the comma (,).

Example

[
   {
      "Name": "Albert Don",
      "City": "New York",
      "SSID": 17728839
   },
   {
      "Name":"John Carter",
      "City":"Ohio",
      "SSID":224544
   },
   {
      "Name":"Milly Lucas",
      "City":"Netherlands",
      "SSID":44903
   }
]

Output

PS E:\scripts\Powershell> Get-Content .\test.json | ConvertFrom-Json
Name       City       SSID
----       ----       ----
Albert Don New York 17728839
John Carter Ohio 224544
Milly Lucas Netherlands 44903

You can convert the output table to the Json format using Convertto-Json cmdlet. See the example below.

Get-Service | Select Name, DisplayName, Status,StartType | Select –First 3
| ConvertTo-Json

Output

PS E:\scripts\Powershell> Get-
Service | Select Name, DisplayName, Status,StartType | Select -
First 3 | ConvertTo-Json
[
   {
      "Name": "AarSvc_69f5c",
      "DisplayName": "Agent Activation Runtime_69f5c",
      "Status": 1,
      "StartType": 3
   },
   {
      "Name": "AdobeARMservice",
      "DisplayName": "Adobe Acrobat Update Service",
      "Status": 4,
      "StartType": 2
   },
   {
      "Name": "AdobeFlashPlayerUpdateSvc",
      "DisplayName": "Adobe Flash Player Update Service",
      "Status": 1,
      "StartType": 3
   }
]

In the above example, individual services are split into a set of arrays.

Updated on: 18-Dec-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements