PoweShell中JSON嵌套哈希表的输出整个内容

时间:2019-02-04 05:42:40

标签: arrays json powershell hash expand

如何在一行中将嵌套的JSON哈希表的全部内容输出到PSO?

$json = @"
{
    "outer": "value1",
    "outerArray": [
        "value2",
        "value3"
    ],
    "outerHash": {
        "inner": "value4",
        "innerArray": [
            "value5",
            "value6"
        ],
        "innerHash": {
            "innermost1": "value7",
            "innermost2": "value8",
            "innermost3": "value9"
        }
    }
}
"@

当前行为:仅显示一个“级别”

$json | ConvertFrom-Json
outer  outerArray       outerHash                                              
-----  ----------       ---------                                              
value1 {value2, value3} @{inner=value4; innerArray=System.Object[]; innerHash=}

所需行为:递归扩展并显示所有哈希/数组内容

$json | ConvertFrom-Json
outer  outerArray       outerHash                                              
-----  ----------       ---------                                              
value1 {value2, value3} @{inner=value4; innerArray=@(value5, value6); innerHash=@{innermost1=value7; innermost2=value8; innermost3=value9}}

以下内容似乎在主题上引起轰动,但未达到预期的效果: PowerShell Hashtable from JSON PSCustomObject to Hashtable How to output multiple hash tables in Powershell

1 个答案:

答案 0 :(得分:0)

用户atscripter向包'ConvertTo-Expression'的所有者发送以下消息:

当我尝试修改PowerShell的默认行为时遇到了您的“ flatten-object”文章。我寻求了关于stackoverflow和technet的帮助,而不是从头开始编写代码,我想知道这有多么困难要调整“展平对象”以达到所需的效果吗?似乎该功能确实很难遍历对象,因为我只是不够熟练,无法使它们以所需的格式输出。非常感谢!

为此,您不必重写flatten-object cmdlet或ConvertTo-Expression cmdlet。
您只需要遍历 first 级别,然后在每个属性上调用ConvertTo-Expression cmdlet(或本地ConvertTo-Json cmdlet):

PowerShell 格式:

$Properties = @{}
($Json | ConvertFrom-Json).PSObject.Properties |
    ForEach-Object {$Properties.($_.Name) = $_.Value |
        ConvertTo-Expression -Expand -1}
[PSCustomObject]$Properties

结果:

outer    outerArray        outerHash
-----    ----------        ---------
'value1' 'value2','value3' [PSCustomObject]@{'inner'='value4';'innerArray'='value5','value6';'innerHash'=[PSCustomObject]@{'innermost1'='value7';'innermost2'='value8';'innermost3'='value9'}}

Json 格式:

($Json | ConvertFrom-Json).PSObject.Properties |
    ForEach-Object {$Properties.($_.Name) = $_.Value |
        ConvertTo-Json -Depth 5 -Compress}

结果(Json)格式略有不同

outer    outerArray          outerHash
-----    ----------          ---------
"value1" ["value2","value3"] {"inner":"value4","innerArray":["value5","value6"],"innerHash":{"innermost1":"value7","innermost2":"value8","innermost3":"value9"}}