尝试使用JQ合并2个JSON文档 [英] Trying to merge 2 JSON documents using JQ

查看:17
本文介绍了尝试使用JQ合并2个JSON文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用JQ CLI将JSON从一个文档合并到另一个文档。我面临的问题是,我根据属性的值而不是数字数组索引进行选择

第一个文件包含一段JSON jqest.json:

{
  "event": [
    {
      "listen": "test",
      "script": {
        "exec": [],
        "type": "text/javascript"
      }
    }
  ]
}

第二个文件是我要在其中将JSON合并到";Account&Quottion.json下的位置:

{
  "item": [
    {
      "name": "accounts",
      "item": [
        {
          "name": "Retrieves the collection of Account resources."
        }
      ]
    },
    {
      "name": "accounts mapped",
      "item": [
        {
          "name": "Retrieves the collection of AccountMapped resources."
        }
      ]
    }
  ]
}

我尝试做的是将其合并到";Account";下,并在";name";下:";检索帐户资源的集合。";我使用命令:

jq -s '
   .[0].event += .[1].item |
   map(select(.name=="accounts")) |
   .[].item
' jqtest.json collection.json

但在执行时不会输出任何内容。JQ哪里出了问题,或者有没有其他工具可以用来完成此任务?

{
  "item": [
    {
      "name": "accounts",
      "item": [
        {
          "name": "Retrieves the collection of Account resources.",
          "event": [
            {
              "listen": "test",
              "script": {
                "exec": [],
                "type": "text/javascript"
              }
            }
          ]
        },
        {
          "name": "accounts mapped",
          "item": [
            {
              "name": "Retrieves the collection of AccountMapped resources."
            }
          ]
        }
      ]
    }
  ]
}

推荐答案

要合并两个对象,可以使用obj1 + obj2。因此,obj1 += obj2可用于将一个对象(obj2)合并到另一个现有对象(obj1)。

也许这就是您要使用的。如果是这样的话,您在生成要合并到的对象的表达式周围缺少了括号(导致代码被错误解析),您有向后+=的操作数,您实际上没有在+=的两侧生成正确的对象(甚至根本没有对象),并且您没有缩小输出范围(意外地在输出中包括了jqtest)。

已修复:

jq -s '
    ( .[1].item[] | select( .name == "accounts" ) | .item[] ) += .[0] | .[1]
' jqtest.json collection.json

Demo在jqplay上

我发现以下内容更清晰(减少了脑力开销):

jq -s '
   .[0] as $to_insert |
   .[1] | ( .item[] | select( .name == "accounts" ) | .item[] ) += $to_insert
' jqtest.json collection.json

Demo

这就是说,我会避免发出声音而支持--argfile

jq --argfile to_insert jqtest.json '
    ( .item[] | select( .name == "accounts" ) | .item[] ) += $to_insert
' collection.json

Demo在jqplay上

这篇关于尝试使用JQ合并2个JSON文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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