Powershell:以递归方式复制JSON属性

时间:2019-01-28 10:35:23

标签: json powershell

我正在尝试编写一个简单的powershell脚本来获取file1.json中的键/值列表,并从file2.json更新这些键的值

我遇到的问题是那些可以嵌套的属性,我不知道键的名称。可能存在任何深度的嵌套,因此潜在地需要递归函数来迭代并搜索这些吗?

我可以遍历PSCustomObject以获得键列表,但是当它涉及到它的嵌套部分时,我很挣扎。任何帮助将是巨大的!

使用PS v5

更新:还需要添加未找到的密钥

1 个答案:

答案 0 :(得分:1)

尝试一下(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"