[英]Extend JSON with another in PowerShell
是否有一些簡單的方法可以將一個JSON文件與另一個JSON文件一起擴展,並使用PowerShell將輸出保存到另一個文件中? 目前我正在嘗試編寫一個允許我這樣做的循環函數*,但也許有一個更簡單的解決方案呢?
*迭代轉換為PSCustomObject
的JSON的PSCustomObject
並在需要時替換它們(實際上在下面檢查我的答案 )
編輯:我需要做類似於jquery.extend所做的事情,我的輸入是:
{
"name": "Some name",
"value": 1,
"config": {
"debug": false,
"output": "c:\\"
}
}
和
{
"value": 2,
"config": {
"debug": true
},
"debug": {
"log": true
}
}
我的輸出應該是:
{
"name": "Some name",
"value": 2,
"config": {
"debug": true,
"output": "c:\\"
},
"debug": {
"log": true
}
}
PS通常我需要編寫一個可以從批處理文件運行的腳本,並且不需要第三方庫(僅限於Windows資源)。 我嘗試使用Cscript JavaScript,但是當我發現時,我決定不使用它,解析JSON的唯一內置方法是評估它。
經過大量的反復試驗后,我設法編寫了我的循環函數。
function ExtendJSON($base, $ext)
{
$propNames = $($ext | Get-Member -MemberType *Property).Name
foreach ($propName in $propNames) {
if ($base.PSObject.Properties.Match($propName).Count) {
if ($base.$propName.GetType().Name -eq "PSCustomObject")
{
$base.$propName = ExtendJSON $base.$propName $ext.$propName
}
else
{
$base.$propName = $ext.$propName
}
}
else
{
$base | Add-Member -MemberType NoteProperty -Name $propName -Value $ext.$propName
}
}
return $base
}
$file1 = (Get-Content $args[0]) -join "`n" | ConvertFrom-Json
$file2 = (Get-Content $args[1]) -join "`n" | ConvertFrom-Json
#Out-File produces incorrect encoding
#ExtendJSON $file1 $file2 | ConvertTo-Json | Out-File $args[2]
$output = ExtendJSON $file1 $file2 | ConvertTo-Json
#Save output as BOMless UTF8
[System.IO.File]::WriteAllLines($args[2], $output)
我不知道這是否是實現目標的最簡單方法,但它確實完成了工作。 這也是如何組合\\ combine \\ merge兩個PSCustomObject
的答案,這似乎沒有人問過(也許我在這里打開門)。 我幾乎傾向於重寫這個問題,但我的直覺告訴我可能有不同的方法使用PowerShell擴展JSON,這不一定需要將我的JSON文件轉換為PSCustomObject
。
如果您運行的是PowerShell 3.0或更高版本,則可以使用內置的ConvertFrom-Json \\ ConvertTo-Json cmdlet。
如果您堅持使用PS 2.0,請查看PowerShell和JSON項目或此模塊 之間的轉換 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.