如何使用 PowerShell 将嵌套 JSON 散列 table 的内容输出到 PSO?

How to output the content of a nested JSON hash table to a PSO using PowerShell?

如何在一行中将嵌套 JSON 散列 table 的全部内容输出到 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=}

期望的行为:递归展开并显示所有 hash/array 内容

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

下面好像刷题了但是没有达到预期的效果: PSCustomObject to Hashtable How to output multiple hash tables in Powershell

用户atscripter sends the following message to the owners of the package 'ConvertTo-Expression':

"我在尝试修改 PowerShell 的默认行为时看到了您的“flatten-object”文章。我在 Whosebug 和 technet 上寻求帮助,而不是从头开始编写代码,我想知道调整 "flatten-object" 以达到预期效果有多困难?似乎该函数完成了遍历对象的困难部分,我只是不够熟练,无法让它们输出所需的内容格式。非常感谢您的输入!"

您不必为此重写 flatten-object cmdlet or 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"}}