在PowerShell中使用另一个扩展JSON

jah*_*ahu 4 powershell json

是否有一些简单的方法将一个JSON文件扩展为另一个JSON文件,并使用PowerShell将输出保存到另一个文件?目前我正在尝试编写一个允许我这样做的循环函数*,但也许有一个更简单的解决方案呢?

*迭代转换为a的JSON属性PSCustomObject并在需要时替换它们(实际上在下面检查我的答案)

编辑:我需要做类似于jquery.extend所做的事情,我的输入是:

{
    "name": "Some name",
    "value": 1,
    "config": {
        "debug": false,
        "output": "c:\\"
    }
}
Run Code Online (Sandbox Code Playgroud)

{
    "value": 2,
    "config": {
        "debug": true
    },
    "debug": {
        "log": true
    }
}
Run Code Online (Sandbox Code Playgroud)

我的输出应该是:

{
    "name": "Some name",
    "value": 2,
    "config": {
        "debug": true,
        "output": "c:\\"
    },
    "debug": {
        "log": true
    }
}
Run Code Online (Sandbox Code Playgroud)

PS通常我需要编写一个可以从批处理文件运行的脚本,并且不需要第三方库(仅限于Windows资源).我尝试使用Cscript JavaScript,但是当我发现时,我决定不使用它,解析JSON的唯一内置方法是评估它.

jah*_*ahu 9

经过大量的反复试验后,我设法编写了我的循环函数.

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)
Run Code Online (Sandbox Code Playgroud)

我不知道这是否是实现目标的最简单方法,但它确实完成了工作.这也是如何组合\ combine\merge两个PSCustomObjects的答案,这似乎没有人问过(也许我在这里打开了大门).我几乎倾向于重写这个问题,但我的直觉告诉我可能有不同的方法使用PowerShell扩展JSON,这不一定需要将我的JSON文件转换为PSCustomObject.