【问题标题】:Powershell with JSON nested objects - cannot get to a property of property of object带有 JSON 嵌套对象的 Powershell - 无法获取对象属性的属性
【发布时间】:2021-03-08 20:45:54
【问题描述】:

我对 Powershell 很陌生,目前我正在尝试从我从 Solr 下载的 JSON 转换一些数据。

JSON 文件如下所示:

{
 "responseHeader": {"status":0, "QTime":2651},
"InitFailures":{}, 
"status":{
   "YX_SERVER.ONE_LOG.2020-11-07_07_49_33": {
         "name":"SERVER.ONE_LOG.2020-11-07_07_49_33",
            "index":{
               "sizeInBytes":69,
                "size":"69 bytes"}},
 "XY_SERVER.TWO_LOG.2020-11-08_09_52_11": {
         "name":"XY_SERVER.TWO_LOG.2020-11-08_09_52_11",
            "index":{
               "sizeInBytes":6487,
                    "size":"6487 bytes"}},
 "ZX_SERVER.THREE_LOG.2020-10-07_07_42_23": {
         "name":"SERVER.THREE_LOG.2020-10-07_07_42_23",
            "index":{
               "sizeInBytes":6977,
               "size":"6977 bytes"
                              }}}}

在第二个状态行下方是具有众多参数的服务器列表(所有名称都不同),我试图深入了解它,但需要嵌套数据的帮助。

我尝试了以下方法:

$list = Get-Content C:\Users\User\Download\cores.json - Raw |convertfrom-json |select-object -ExpandProperty status

然后 $list 向我显示服务器列表,所需的数据在右栏中,但我无法直接访问它。如何构建表格并计算总和,如下所示:

Name                                     Size(inbytes) 
YX_SERVER.ONE_LOG.2020-11-07_07_49_33    69
XY_SERVER.TWO_LOG.2020-11-08_09_52_11    6487
ZX_SERVER.THREE_LOG.2020-10-07_07_42_23  6977

Summary                                  Total size
                                         ?

【问题讨论】:

    标签: json powershell nested-lists select-object


    【解决方案1】:
    $Content = Get-Content .\cores.json
    $Data = $Content | ConvertFrom-Json
    $Status = $Data.status
    $Table = $Status.PSObject.Properties.Value | Foreach-Object {
        [pscustomobject]@{
            name = $_.name
            sizeInBytes = $_.index.sizeInBytes
        }
    }
    $Table
    
    [pscustomobject]@{
        name = 'Total Size:'
        sizeInBytes = ($Table.sizeInBytes | Measure-Object -Sum).Sum
    }
    

    name                                  sizeInBytes
    ----                                  -----------
    SERVER.THREE_LOG.2020-10-07_07_42_23         6977
    XY_SERVER.TWO_LOG.2020-11-08_09_52_11        6487
    SERVER.ONE_LOG.2020-11-07_07_49_33             69
    Total Size:                                 13533
    

    【讨论】:

    • 抱歉 JSON 中的那个错字!我编辑并验证了它。不幸的是,Powershell 6.0 中引入了 -ashashtable 选项。而且我只安装了 5.0。有没有其他方法可以做到这一点?
    • 我已经更新了不支持 -AsHashTable 的旧版本 PowerShell 的答案,在这种情况下,您可以简单地枚举 $Status.PSObject.Properties.Value 成员
    • 这完全有帮助!太感谢了!你太棒了! ^__^
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-17
    • 2017-09-10
    相关资源
    最近更新 更多