我有兩個 JSON 檔案,想將物件集合從一個檔案傳輸到另一個檔案。假設,該from.json檔案包含代表客戶集合的屬性:
"Clients":
[
{
"Name": "Name1",
"Age": "12"
},
{
"Name": "Name2",
"Age": "14"
}
]
to.json檔案包含一個空集合,"Objects: []",必須用來自from.json. toJson變數中的每個物件都必須包含附加屬性 - Id,因此最終,我的“to.json”檔案應如下所示:
"Objects":
[
{
"Id": "{new-id}",
"Name": "Name1",
"Age": "12"
},
{
"Id": "{new-id}",
"Name": "Name1",
"Age": "12"
}
]
我已將兩個檔案轉換為變數:
$fromJson = (Get-Content -Raw -Path {fromPath}) | ConvertFrom-Json
$toJson = (Get-Content -Raw -Path {toPath}) | ConvertFrom-Json
我知道fromJsonto 的物件toJson可以通過以下方式傳輸:
toJson.Objects = fromJson.Clients,但這對我來說還不夠。我認為可以通過遍歷fromJson.Clients陣列來完成,但不知道如何創建物件并將其添加到toJson.Objects集合中。
uj5u.com熱心網友回復:
這是一個更有效的解決方案,基于:
使用的計算性能與
Select-Object,它允許你把新的屬性首先在輸出物件。相反建設陣列的逐個用
=(這是低效的,因為一個新的陣列必須在技術上在每次迭代幕后創建),該解決方案下面就讓PowerShell中收集的輸出物件Select-Object呼叫陣列中的自動(該[array]型別約束即使碰巧只輸出一個物件,也需要確保創建一個陣列。)
# Sample input.
$fromJson = ConvertFrom-Json '{"Clients":[{"Name":"Name1","Age":"12"},{"Name":"Name2","Age":"14"}]}'
$toJson = ConvertFrom-Json '{ "Objects": [] }'
[array] $toJson.Objects =
$fromJson.Clients |
Select-Object @{ Name='Id'; Expression = { [string] (New-Guid) } }, *
$toJson | ConvertTo-Json -Depth 3 # append | Set-Content as needed.
uj5u.com熱心網友回復:
對 PowerShell 有點陌生,但經過一番調查后,提出了以下解決方案:
fromJson.Clients | ForEach-Object {
$_ | Add-Member -MemberType NoteProperty -Name 'Id' -Value ([guid]::NewGuid().Guid.ToString())
$toJson = $_
}
...
$toJson | ConvertTo-Json | Out-File {to.json_path}
坦率地說,不知道這是否是一種“正確”的方式來做到這一點,但通常它適用于那種特殊情況。目前,看不到其他解決方案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/392515.html
