json - 在 PowerShell 中使用另一个扩展 JSON

标签 json powershell

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

*迭代转换为 PSCustomObject 的 JSON 的属性并在需要时更换它们(实际上是 check my answer below )

编辑:我需要做一些类似于 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
    }
}

附言通常我需要编写一个可以从批处理文件中运行的脚本,并且不需要 3rd 方库(仅限于 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)

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

关于json - 在 PowerShell 中使用另一个扩展 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29330627/

相关文章:

javascript - 从 Neo4j 解析复杂的 JSON 结果

c# - 如何在使用 Newtonsoft.Json 序列化 json 时忽略默认值

windows - 动态获取脚本帮助示例部分中的powershell脚本名称

.net - Powershell - IO.Directory - 查找所有子目录中的文件类型

powershell - 使用Powershell测试应用程序链接

json - 如何使用 Codable 协议(protocol)解析带有自定义参数的 JSON

javascript - 如何将数组列表格式化为json

javascript - 如何在 GWT 中将 JSONObject 或 JavaScriptObject 分配给 $wnd[x]?

powershell - 通过Powershell格式化JSON

powershell - 完全路径可执行文件时 PowerShell 中的“意外 token ”