[英]Extend JSON with another in PowerShell
是否有一些简单的方法可以将一个JSON文件与另一个JSON文件一起扩展,并使用PowerShell将输出保存到另一个文件中? 目前我正在尝试编写一个允许我这样做的循环函数*,但也许有一个更简单的解决方案呢?
*迭代转换为PSCustomObject
的JSON的PSCustomObject
并在需要时替换它们(实际上在下面检查我的答案 )
编辑:我需要做类似于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
}
}
PS通常我需要编写一个可以从批处理文件运行的脚本,并且不需要第三方库(仅限于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)
我不知道这是否是实现目标的最简单方法,但它确实完成了工作。 这也是如何组合\\ combine \\ merge两个PSCustomObject
的答案,这似乎没有人问过(也许我在这里打开门)。 我几乎倾向于重写这个问题,但我的直觉告诉我可能有不同的方法使用PowerShell扩展JSON,这不一定需要将我的JSON文件转换为PSCustomObject
。
如果您运行的是PowerShell 3.0或更高版本,则可以使用内置的ConvertFrom-Json \\ ConvertTo-Json cmdlet。
如果您坚持使用PS 2.0,请查看PowerShell和JSON项目或此模块 之间的转换 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.