以下代码将data
和data2
连接起来,并创建一个非规范化的CSV文件。
$str = '{
"data": [
{ "attrs": { "id": "A", "more": "A" },
"relations": [{"id": "r11"}, {"id": "r12"}] },
{ "attrs": { "id": "B", "more": "B" },
"relations": [{"id": "r21"}] }
],
"data2": [
{"id": "r11", "attrs": { "x": "11", "y": "1"}},
{"id": "r12", "attrs": { "x": "12", "y": "2"}},
{"id": "r21", "attrs": { "x": "21", "y": "1"}}
]}'
$json = $str | ConvertFrom-Json
$json.data |
% {
#$data = $null
$data = $_.attrs
$_.relations.id | #select -first 1 |
% {
$d2 = $json.data2 | ? id -eq $_ | select -ExpandProperty attrs
Write-Host -ForegroundColor Green $d2
$d2 | Get-Member -Type Properties | % {
Write-Host -ForegroundColor Red $_
Add-Member -InputObject $data -NotePropertyName $_.Name -NotePropertyValue $_
}
$data
}
} |
ConvertTo-Csv
但是,它得到了以下错误?
Add-Member:
Line |
12 | Add-Member -InputObject $data -NotePropertyName $_.Name - …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Cannot add a member with the name "x" because a member with that name already exists. To overwrite the member anyway, add the Force parameter to your command.
string y=1
1条答案
按热度按时间6g8kf2rb1#
因为
data
中的每个attrs
都可能有多个relation.id
,所以您将attrs
(Add-Member
)两次添加到d2
对象,因此您需要首先解开data
对象(请参阅我对您之前问题的回答:Zip two select list?以创建平面$data
和$data2
对象)。正如在In PowerShell, what's the best way to join two tables into one?的一些答案中所解释的,使用哈希表可能是最简单和最快的:
然后将属性添加到$data对象:
如果您不想重新发明轮子,您还可以使用
Join-Object script
/Join-Object Module
my answer: