Use JSON to Create Objects

by May 9, 2014

JSON is describing objects, similar to XML–but a lot easier. JSON allows for nested object properties, so you can retrieve information from various sources and consolidate them into one custom object.

Have a look. This creates an inventory item containing various computer details:

$json = @"
{
    "ServerName": "$env:ComputerName",
    "UserName": "$env:UserName",
    "BIOS": {
         "Manufacturer" : "$((Get-WmiObject -Class Win32_BIOS).Manufacturer)",
         "Version" : "$((Get-WmiObject -Class Win32_BIOS).Version)",
         "Serial" : "$((Get-WmiObject -Class Win32_BIOS).SerialNumber)"
         },
    "OS" : "$([Environment]::OSVersion.VersionString)"
 }
"@

$info = ConvertFrom-Json -InputObject $json

$info.ServerName
$info.BIOS.Version
$info.OS 

You can then manipulate the resulting objects – retrieve information, or add/update details.

If you made changes to the object, you can use ConvertTo-Json to convert it back into JSON format for serialization:

Twitter This Tip! ReTweet this Tip!