簡體   English   中英

Powershell:遞歸復制 JSON 屬性

[英]Powershell: Copy JSON properties recursively

我正在嘗試編寫一個簡單的 powershell 腳本來獲取 file1.json 中的鍵/值列表,並從 file2.json 更新這些鍵的值

我遇到的問題是那些可以嵌套的屬性,我不知道鍵的名稱。 可能有任何嵌套深度,所以可能需要一個遞歸函數來迭代和搜索這些?

我可以遍歷 PSCustomObject 以獲取鍵列表,但是當它進入嵌套部分時我很掙扎。 任何幫助都會很棒!

使用 PS v5

更新:它還需要添加未找到的密鑰

試試這個(Powershell v3+)。 這個想法是先讀取兩個 JSON 文件,在內存中進行比較,然后再次將第二個(更新的)JSON 導出到文件中。

# function to copy JSON properties from source to target
# obj1: source object
# obj2: target object
# (values will be copied,
# missing properties will be added,
# extra properties will be left untouched)
function Copy_Keys ($obj1, $obj2) {
    # loop properties of source object
    foreach ($property1 in $obj1.PSObject.Properties) {
        $key = $property1.Name
        $value1 = $property1.Value
        $property2 = $obj2.PSObject.Properties.Item($key)
        # check if property exists in target object
        if ($null -ne $property2) {
            $value2 = $property2.Value
            # if both values are objects: compare recursively
            if ($value1 -is [PSObject] -and $value2 -is [PSObject]) {
                Copy_Keys $value1 $value2
            }
            # else simply copy the value
            else {
                $obj2.$key = $value1
            }
        }
        # property does not exist: add it
        else {
             $obj2 | Add-Member -Type NoteProperty -Name $key -Value $value1
        }
    }
}

# Read JSON from source(s)
$obj1 = Get-Content "file1.json" | ConvertFrom-Json
$obj2 = Get-Content "file2.json" | ConvertFrom-Json

# Copy the properties
Copy_Keys $obj1 $obj2

# Update file2 by re-exporting the JSON
$obj2 | ConvertTo-Json | Out-File "file2.json"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM