问题
I am exporting the JSON from an Azure Resource Group to a JSON file like this:
Export-AzureRmResourceGroup -ResourceGroupName $SourceResourceGroupName -Path $filename
Then I am getting the JSON contents of the file, then applying it to a variable:
$SourceJSON = Get-Content $filename -Raw
I then want to turn (convert) this into a PowerShell object:
$SourceJSONRG = $SourceJSON | ConvertFrom-Json
I then have a look at the resources from with the object:
$SourceJSONRG.resources
But the storageProfile section is blank:
Whereas looking at the JSON ($SourceJSON) in comparison, the storageProfile is not blank:
I have tried using the Format-Custom -Depth option to go down much deeper:
$SourceJSONRG = $SourceJSON | ConvertFrom-Json
$SourceJSONRG = $SourceJSONRG | Format-Custom -Depth 99
But this puts in “class PSCustomObject” everywhere which I don’t want.
The ultimate thing I am trying to do here is convert the JSON to a PowerShell object, make changes to it e.g. change the the URI for a disk, then convert back to JSON to use it for deployment to Azure. In other words, converting the JSON to a PowerShell object makes it much easier for me to work with it.
New-AzureRmResourceGroupDeployment -ResourceGroupName $TargetResourceGroupName -TemplateFile "C:\Users\marc\AppData\Local\Temp\test20692192.json"
回答1:
I think that is just an issue of stopping displaying nested values but that does not mean that the values are missing.
You can see that with the following example. Given a sample JSON string like the following and converting it to a JSON object results in the same 'missing' values
$jsonString = @"
{
"root": {
"nested1": {
"nested11": {
"leaf1": "some value",
"leaf2": "some other value"
}
},
"nested2": {
"nested22": {
"leaf1": "some value",
"leaf2": "some other value"
}
}
}
}
"@
$obj = ConvertFrom-Json $jsonString
$obj
Output:
root
----
@{nested1=; nested2=}
But when accessing and modifying the actual object's properties and converting it back to a JSON string you will see everything works
$obj.root.nested1.nested11.leaf1 = "42"
$jsonString = ConvertTo-Json $obj -Depth 5
Write-Host $jsonString
Output:
{
"root": {
"nested1": {
"nested11": {
"leaf1": "42",
"leaf2": "some other value"
}
},
"nested2": {
"nested22": {
"leaf1": "some value",
"leaf2": "some other value"
}
}
}
}
来源:https://stackoverflow.com/questions/39008020/converting-json-to-powershell-object-and-converting-powershell-back-to-json