[英]Flattening a Sub-Array in a Powershell Object, including parent object property
Given the following JSON给定以下 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:其中,我很容易转换成 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如何展平子阵列的
things
并包含来自父 object 的key
,以便我的结果集是
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.您循环到每个键,然后循环到每个事物,因为您希望每个事物有 1 个结果,并使用当前键、id 和名称构建一个 PSObject。
Here you go.这里是 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 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:您可以使用 select 的内置展平,如下所示:
($json | ConvertFrom-Json) | ($json | ConvertFrom-Json) | Select-Object key -ExpandProperty things
Select-Object 键-ExpandProperty 事物
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.