JSON for PowerShell Part 1

JSON, otherwise known as “Javascript object notation” is a fundamental way of representing key/value pairs. In database terms this translates as a field name (the key) and the field contents (the value).

Let’s show a single contact record in JSON, with two phone numbers, work and home.

{    
"FName":"Myron", 
"Lname":"Kapoodle",
"Address1":"123 Anywhere Lane",
 "Address2":"Apartment 404",
 "City":"BigTown",
  "State":"AZ",
    "Zip":"12345",
    "PhoneNumbers":[       
 {"type":"home","number":"920 234-3424" },
 {"type":"work","number":"920 535-2312"  }
   ]
}

A couple of characteristics:

The complete JSON structure is enclosed in its own curly brackets
If there is more than one record, then the whole structure is contained with square brackets, and the individual records are separated by a comma. This applies to nested records too, as in the case of the two phone numbers for the individual.

Below is the notation for two contact records. In this case, the whole structure is enclosed in square brackets. The individual contact records are enclosed in curly brackets and the two records are separated by a comma.

[    
{"FName":"Myron",
 "Lname":"Kapoodle",
 "Address1":"123 Anywhere Lane",
 "Address2":"Apartment 404",
 "City":"BigTown",
 "State":"AZ",
"Zip":"12345",
"PhoneNumbers":[ {"type":
"home","number":"920 234 3424"},
"type":"work","number":"920 535-2312"}]
}
,
{
"FName":"Myra",
Lname":"Kapoodlova",
"Address1":"123 Anywhere Lane",
"Address2":"Apartment 404",
"City":"BigTown",
"State":"AZ",
"Zip":"12345",
"PhoneNumbers":[ {"typee":
"home","number":"920 234-3424"},
{"type":"work","number":"920 535-2312"}]
}
]

When writing JSON, its helpful to have an automatic checker for syntax. One such is JSONLint at http://jsonlint.com. In Visual Studio Code you can use the Shift-Alt-F within the editor to nicely format JSON code.

The rules of JSON are summarized at JSONLint, but basically include:

  • Keys are enclosed in double quotes.
  • All data elements that are not a boolean or integers are enclosed in double-quotes.
  • Individual entities (i.e. records) are separated by a comma
  • Each key/value pair is separated by a comma
  • Each entity is enclosed by curly brackets.

Since I’m editing JSON in Visual Studio Code, there is more how VSC handles JSON in the Microsoft docs at JSON editing in Visual Studio Code.

Powershell has a two commands that deal directly with JSON.

PS M:\PSFolder> get-command *json*     

CommandType     Name                    Version    Source
-----------     ----                    -------    ------
Cmdlet          ConvertFrom-Json        3.1.0.0    Microsoft.PowerShell.Utility
Cmdlet          ConvertTo-Json          3.1.0.0    Microsoft.PowerShell.Utility


These convert Powershell objects to and from JSON notation. More on that in Part 2.

Leave a comment