以下代碼加入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
uj5u.com熱心網友回復:
因為每個attrsindata可能有多個relation.ids,所以您將attrs( Add-Member) 添加到物件兩次d2,因此您需要先解開data物件(請參閱我對您上一個問題的回答:Zip two select list? to create flat $dataand $data2objects)。
正如在 PowerShell 中的幾個答案中所解釋的那樣,將兩個表合并為一個表的最佳方法是什么?,使用哈希表可能是最簡單和最快的:
$Hashtable = @{}
$Data2.ForEach{ $Hashtable[$_.id] = $_}
$Hashtable
Name Value
---- -----
r12 @{id=r12; x=12; y=2}
r21 @{id=r21; x=21; y=1}
r11 @{id=r11; x=11; y=1}
將屬性添加到 $data 物件:
$data.ForEach{
$_ |Add-Member -NotePropertyName x -NotePropertyValue $HashTable[$_.relation].x
$_ |Add-Member -NotePropertyName y -NotePropertyValue $HashTable[$_.relation].y
}
$data |Format-Table
relation id more x y
-------- -- ---- - -
r11 A A 11 1
r12 A A 12 2
r21 B B 21 1
如果您不想重新發明輪子,您不妨使用Join-Object script/我的答案:Join-Object Module
$data |Join $data2 -on relation -eq id |Format-Table
relation id more x y
-------- -- ---- - -
r11 A A 11 1
r12 A A 12 2
r21 B B 21 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/534712.html
標籤:电源外壳
上一篇:如果匹配擴展名,則使用powershell移動檔案夾
下一篇:獲取最大字串
