Using PowerShell to Read and Write JSON

This blog provides a simple example of using PowerShell to read and write JSON.

Using PowerShell to Write JSON

In this example, we first create a PowerShell object with some sample properties and nested objects. We then use the ConvertTo-Json cmdlet to convert the PowerShell object to a JSON string. Finally, we use the Set-Content cmdlet to save the JSON string to a file.

This example shows how to read and write JSON using PowerShell, and can be customized to fit the specific needs of your JSON data.

$obj = @{
    "PropertyName" = "PropertyValue"
    "ObjectName" = @{
        "ObjectPropertyName" = "ObjectPropertyValue"
    }
}

# Convert object to JSON
$json = $obj | ConvertTo-Json

# Save JSON to file
$json | Set-Content -Path C:\alkane\example.json

Using PowerShell to Read JSON

In this example, we first load a JSON file using the Get-Content cmdlet and pass the -Raw parameter to read the entire file as a single string. We then use the ConvertFrom-Json cmdlet to convert the JSON string to a PowerShell object. We can then access specific properties within the JSON object using dot notation.

# Load JSON file
$json = Get-Content -Path C:\alkane\example.json -Raw | ConvertFrom-Json

# Access JSON properties
$json.PropertyName
$json.ObjectName.PropertyName

Using PowerShell to Iterate Through JSON

Let’s suppose our JSON file has more than one object with multiple properties (key/value pairs) like so:

$obj = @{
    "ObjectName1" = @{
        "Object1PropertyName1" = "Object1PropertyValue1"
        "Object1PropertyName2" = "Object1PropertyValue2"
    }
    "ObjectName2" = @{
        "Object2PropertyName1" = "Object2PropertyValue1"
        "Object2PropertyName2" = "Object2PropertyValue2"
    }
}

# Convert object to JSON
$json = $obj | ConvertTo-Json

# Save JSON to file
$json | Set-Content -Path C:\alkane\example.json

We might then want to loop through these objects and properties to read each value.  We can do this like so:

# Load JSON file
$json = Get-Content -Path C:\alkane\example.json -Raw | ConvertFrom-Json

# Loop through the objects in the JSON data
foreach ($object in $json.PSObject.Properties) {

    Write-Host "Object name: $($object.Name)"
  
    $objectproperties = Get-Member -InputObject $object.Value -MemberType NoteProperty
  
    foreach($property in $objectproperties) {
        Write-Host "Property name: $($property.Name)"
        Write-Host "Property value: $($object.Value.($property.Name))"
    }

}