Powershell:递归复制JSON属性
我正在尝试编写一个简单的powershell脚本,以获取file1.json中的键/值列表,并从file2.json更新这些键的值 我遇到的问题是,这些属性可以是嵌套的,而我不知道键的名称。嵌套可能有任何深度,因此可能需要递归函数来迭代和搜索这些嵌套 我可以在PSCustomObject上循环以获得一个键列表,但是当它到达这个嵌套部分时,我很难找到它。任何帮助都会很好 使用PSV5 更新:还需要添加找不到的密钥试试这个(Powershell v3+)。首先读取两个JSON文件,在内存中进行比较,然后再次将第二个(更新的)JSON导出到文件中Powershell:递归复制JSON属性,json,powershell,Json,Powershell,我正在尝试编写一个简单的powershell脚本,以获取file1.json中的键/值列表,并从file2.json更新这些键的值 我遇到的问题是,这些属性可以是嵌套的,而我不知道键的名称。嵌套可能有任何深度,因此可能需要递归函数来迭代和搜索这些嵌套 我可以在PSCustomObject上循环以获得一个键列表,但是当它到达这个嵌套部分时,我很难找到它。任何帮助都会很好 使用PSV5 更新:还需要添加找不到的密钥试试这个(Powershell v3+)。首先读取两个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"
请编辑问题并包含一些示例数据和所需的输出。嗨,Marsze,这是一个很好的循环键的方法-比我现有的解决方案更整洁,但是我如何根据此输出更新文件2中的键?太棒了,非常感谢!救了我好几个小时@PaulEvans您应该将现有解决方案的代码放入原始问题中。很高兴这对你有用,如果有任何问题,请告诉我。