Powershell with JSON nested objects - cannot get to a property of property of object

2.7k views Asked by At

I'm quite new to Powershell and currently I'm trying to convert some data from JSON I downloaded from Solr.

The JSON file looks like:

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

Below the second status line is the list of the servers with numerous parameters(all names are different), I tried to go deeper into it, but need help with nested data.

I tried the following:

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

Then $list shows me the list of servers and the data needed is in the right column but I cannot access it directly. How can I build the table and calculate the sum just like follows:

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
                                         ?
1

There are 1 answers

3
iRon On BEST ANSWER
$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