将JSON转换为PowerShell对象,将PowerShell转换回JSON。

3
我正在将Azure资源组中的JSON导出为以下格式的JSON文件:
```json

{ "example": "示例" }

```
Export-AzureRmResourceGroup -ResourceGroupName $SourceResourceGroupName -Path $filename

然后我获取文件的JSON内容,将其应用到一个变量中:

$SourceJSON = Get-Content $filename -Raw 

我想将这个转换为PowerShell对象:

$SourceJSONRG = $SourceJSON | ConvertFrom-Json 

我随后查看对象内部的资源:

$SourceJSONRG.resources

但是storageProfile部分为空:

enter image description here

然而,通过比较JSON($SourceJSON),可以发现storageProfile不为空:

enter image description here

我已经尝试使用Format-Custom -Depth选项进行更深入的查看:

$SourceJSONRG = $SourceJSON | ConvertFrom-Json
$SourceJSONRG = $SourceJSONRG | Format-Custom -Depth 99

但是这样会在所有地方加上“class PSCustomObject”,我不想要这个。

enter image description here

我想要做的最终目标是将JSON转换为PowerShell对象,对其进行更改,例如更改磁盘的URI,然后将其转换回JSON以便用于部署到Azure。换句话说,将JSON转换为PowerShell对象使我更容易处理它。
New-AzureRmResourceGroupDeployment -ResourceGroupName $TargetResourceGroupName -TemplateFile "C:\Users\marc\AppData\Local\Temp\test20692192.json"
1个回答

4

我认为这只是停止显示嵌套值的问题,但这并不意味着值不存在。

您可以通过以下示例查看。给定类似以下的样本JSON字符串,并将其转换为JSON对象将导致相同的“缺失”值。

$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字符串时,您会发现一切正常。

$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"
                                              }
                             }
             }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接