Question:
It looks like the way I am expecting this to work doesn’t. I want multiple objects returned, but it seems to be returning just one. It is beyond me how I do it.
A very simple JSON file:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
{ "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#", "contentVersion": "1.0.0.0", "parameters": { "storageAccountName": { "value": "sa01" }, "virtualNetworkName": { "value": "nvn01" } } } |
I want to dynamically add the parameters and their values into a nice pscustomobject (that would look like the following with the above data):
1 2 3 4 5 |
ParameterName | Value =========================== storageAccountName | sa01 virtualNetworkName | nvn01 |
What I don’t understand is why the following returns one object:
1 2 3 4 5 6 |
$TemplateParametersFile = "C:\Temp\deploy-Project-Platform.parameters.json" $content = Get-Content $TemplateParametersFile -Raw $JsonParameters = ConvertFrom-Json -InputObject $content $JsonParameters.parameters | Measure-Object |
Whilst writing this, I eventually found a solution that get’s what I want, which I’ll post in the answer section. Feel free to school me and improve…
Answer:
I would do things a little differently, skipping the hashtable, and using the hidden PSObject
property. So, picking up after you have the JSON data stored in $content
, I would do something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#Convert JSON file to an object $JsonParameters = ConvertFrom-Json -InputObject $content #Create new PSObject with no properties $oData = New-Object PSObject #Loop through properties of the $JsonParameters.parameters object, and add them to the new blank object $JsonParameters.parameters.psobject.Properties.Name | ForEach{ Add-Member -InputObject $oData -NotePropertyName $_ -NotePropertyValue $JsonParameters.parameters.$_.Value } $oData |
By the way, it had issues converting the JSON you posted, I had to add quotes around the two values, such as "value": "sa01"
.