合并两个json对象 [英] Merge two json objects

查看:161
本文介绍了合并两个json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下输入-2个json文件,一个是基础文件,第二个包含相同的属性,但值不同,我想合并这些对象.

I have the following inputs - 2 json files one is the base one and the second contains the same properties but the different values, I'd like to merge that objects.

例如:

{
  a:{
    b:"asda"
  }
  c: "asdasd"
}

第二个文件:

{
  a:{
   b:"d"
  }
}

结果应该是这样的:

{a:{b:"d"},c:"asdasd"}

使用powershell可以吗?

Is that is possible with powershell?

推荐答案

$Json1 | Join $Json2 -Merge {$Right.$_} | ConvertTo-Json (请参见下面的更新)

($Json1 ConvertFrom-Json) | Merge ($Json2 ConvertFrom-Json) | ConvertTo-Json

结果:

{
    "c":  "asdasd",
    "a":  {
              "b":  "d"
          }
}

您可能会考虑不覆盖左侧的值:

You might consider not to overwrite the left value:

($Json1 ConvertFrom-Json) | Join ($Json2 ConvertFrom-Json) | ConvertTo-Json

在这种情况下,结果将是:

In that case the result will be:

{
    "c":  "asdasd",
    "a":  [
              {
                  "b":  "asda"
              },
              {
                  "b":  "d"
              }
          ]
}

有关详细信息,请参见: https://stackoverflow.com/a/45483110/1701026

For details see: https://stackoverflow.com/a/45483110/1701026

更新2019-11-16
-Merge参数已用完,并已除以-Discern-Property参数(对重大更改感到抱歉).好消息是,对象合并的默认参数设置位于名为Merge-Object(别名为Merge)的代理命令中,该命令将相关语法简化为:$Object1 | Merge $Object2.有关详细信息,请参见自述文件或嵌入式帮助.

Update 2019-11-16
The -Merge parameter has been depleted and divided over the -Discern and -Property parameters (sorry for the breaking change). The good news is that the default parameter settings for an object merge are accommodated in a proxy command named Merge-Object (alias Merge) which simplifies the concerned syntax to just: $Object1 | Merge $Object2. For details, see readme or embedded help.

这篇关于合并两个json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆