将JSON转换为PowerShell对象并将PowerShell转换回JSON [英] Converting JSON to PowerShell object and converting PowerShell back to JSON
问题描述
我正在将JSON从Azure资源组导出到JSON文件,如下所示:
I am exporting the JSON from an Azure Resource Group to a JSON file like this:
Export-AzureRmResourceGroup -ResourceGroupName $SourceResourceGroupName -Path $filename
然后我要获取文件的JSON内容,然后将其应用于变量:
Then I am getting the JSON contents of the file, then applying it to a variable:
$SourceJSON = Get-Content $filename -Raw
然后我想将其转换(转换)为PowerShell对象:
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
但是storageProfile
部分为空白:
对比来看JSON($SourceJSON
),storageProfile
不是空白:
Whereas looking at the JSON ($SourceJSON
) in comparison, the storageProfile
is not blank:
我尝试使用Format-Custom -Depth
选项进行更深入的研究:
I have tried using the Format-Custom -Depth
option to go down much deeper:
$SourceJSONRG = $SourceJSON | ConvertFrom-Json
$SourceJSONRG = $SourceJSONRG | Format-Custom -Depth 99
但这会在我不想要的任何地方放入"class PSCustomObject
".
But this puts in "class PSCustomObject
" everywhere which I don’t want.
我在这里要做的最终事情是将JSON转换为PowerShell对象,对其进行更改,例如更改磁盘的URI,然后转换回JSON以将其用于部署到Azure.换句话说,将JSON转换为PowerShell对象可以使我更轻松地使用它.
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"
推荐答案
我认为这只是停止显示嵌套值的问题,但这并不意味着值会丢失.
I think that is just an issue of stopping displaying nested values but that does not mean that the values are missing.
您可以通过以下示例看到这一点.给定一个类似于以下示例的JSON字符串并将其转换为JSON对象会导致相同的缺失"值
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
输出:
root
----
@{nested1=; nested2=}
但是当访问和修改实际对象的属性并将其转换回JSON字符串时,您会看到一切正常
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
输出:
{
"root": {
"nested1": {
"nested11": {
"leaf1": "42",
"leaf2": "some other value"
}
},
"nested2": {
"nested22": {
"leaf1": "some value",
"leaf2": "some other value"
}
}
}
}
这篇关于将JSON转换为PowerShell对象并将PowerShell转换回JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!