Home > OS >  Flattening a Sub-Array in a Powershell Object, including parent object property
Flattening a Sub-Array in a Powershell Object, including parent object property

Time:11-26

Given the following JSON

[
  {
    "key": "James",
    "things": [
      {
        "id": 123,
        "name": "PRD"
      },
      {
        "id": 124,
        "name": "PRE"
      }
    ]
  },
  {
    "key": "Susan",
    "things": [
      {
        "id": 125,
        "name": "PRF"
      },
      {
        "id": 126,
        "name": "PRG"
      }
    ]
  }
]

Which, I've easily converted into a Powershell object:

$json = '[{"key":"James", "things":[{"id":123,"name":"PRD"},{"id":124,"name":"PRE"}]},{"key":"Susan", "things":[{"id":125,"name":"PRF"},{"id":126,"name":"PRG"}]}]'

$obj = $json | ConvertFrom-Json 

How do I flatten the sub-array things and include the key from the parent object, so that my result set is

key    id name
---    -- ----
James 123 PRD  
James 124 PRE  
Susan 125 PRF
Susan 126 PRG

I've used the following to flatten the sub-array:

$obj | % { $_.things}  

Which returns me

 id name
 -- ----
123 PRD  
124 PRE  
125 PRF
126 PRG

But, I can't quite figure out what to do next.

Any help would be much appreciated.

CodePudding user response:

You loop into each key, then loop into each things, since you want 1 result per thing, and build a PSObject using the current key, id and name.

Here you go.

# initial code sample
$json = '[{"key":"James", "things":[{"id":123,"name":"PRD"},{"id":124,"name":"PRE"}]},{"key":"Susan", "things":[{"id":125,"name":"PRF"},{"id":126,"name":"PRG"}]}]'
$obj = $json | ConvertFrom-Json 

# Loop needed to flatten the object.
foreach ($i in $obj) {
    foreach ($t in $i.things) {
        [PSCustomObject]@{
            key  = $i.key
            id   = $t.id
            name = $t.name
        }
    }
}

Output

key    id name
---    -- ----
James 123 PRD
James 124 PRE
Susan 125 PRF
Susan 126 PRG
  • Related