简体   繁体   中英

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

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.

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

you can use built-in flattening with select as follows:

($json | ConvertFrom-Json) | Select-Object key -ExpandProperty things

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM