I thought I should give back to the forum/community which has helped me a lot over the years. I've seen a lot of people writing PowerShell which builds text manually for JSON output. That's really fraught with danger in lots of ways.
The following PowerShell is an example of the _correct_ way to build a proper multidimensional object within PowerShell to pass to ConvertTo-JSON.
$jsonRoot = @{} $jsonPrtgNode = @{} $jsonResultsNode = @() $resultHashTableItem = @{ "channel" = "Item Total" "unit" = "Count" "mode" = "Absolute" "showChart" = "1" "showTable" = "0" "warning" = "0" "float" = "0" "value" = "123" } $jsonResultsNode += $resultHashTableItem $resultHashTableItem = @{ "channel" = "Item Exit Total" "unit" = "Count" "mode" = "Absolute" "showChart" = "1" "showTable" = "0" "warning" = "0" "float" = "0" "value" = "456" } $jsonResultsNode += $resultHashTableItem $statusHashTableItem = @{ "text" = "Completed Sucessfully" } $jsonResultsNode += $statusHashTableItem $jsonPrtgNode.Add("result",$jsonResultsNode) $jsonRoot.Add("prtg",$jsonPrtgNode) $jsonRoot | ConvertTo-Json -Depth 3
The output you will get from this example is the following
{ "prtg": { "result": [ { "channel": "Item Total", "unit": "Count", "showChart": "1", "warning": "0", "value": "123", "mode": "Absolute", "showTable": "0", "float": "0" }, { "channel": "Item Exit Total", "unit": "Count", "showChart": "1", "warning": "0", "value": "456", "mode": "Absolute", "showTable": "0", "float": "0" }, { "text": "Completed Sucessfully" } ] } }
I hope this helps someone avoid trying to build a large text/string output and makes their PowerShell JSON creation a lot more robust.
Add comment