【问题标题】:Trying to merge 2 JSON documents using JQ尝试使用 JQ 合并 2 个 JSON 文档
【发布时间】:2021-12-17 16:29:01
【问题描述】:

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

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

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

第二个文件是我想将 JSON 合并到“accounts”collection.json 下的地方:

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

我要做的是将它合并到“帐户”和“名称”下:“检索帐户资源的集合。”我使用命令:

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."
            }
          ]
        }
      ]
    }
  ]
}

【问题讨论】:

  • 您能否提供一个您期望的输出示例?不清楚是什么 不清楚«merge it under "accounts"» 是什么意思,不清楚«merge it under "accounts" and under "name"» 是什么意思,不清楚你想要这两个中的哪一个。
  • 这不是有效的 JSON。
  • 我编辑了上面的问题并在上面添加了所需的输出
  • 抱歉,我没有注意到编辑。 (我没有收到通知是因为你没有在评论中使用@ikegami 和/或因为我圣诞节太忙了。)

标签: json jq


【解决方案1】:

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

也许这就是你想要使用的。如果是这样,您在生成要合并到的对象的表达式周围缺少括号(导致代码被错误解析),您有 += 的操作数向后,您实际上并没有在 @987654329 的每一侧产生正确的对象@(甚至是对象),并且您没有缩小输出范围(不小心在输出中包含 jqtest)。

固定:

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

Demojqplay

我发现以下更清晰(更少的精神开销):

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

Demojqplay

【讨论】:

    猜你喜欢
    • 2022-10-24
    • 2013-11-01
    • 1970-01-01
    • 2021-01-11
    • 1970-01-01
    • 2019-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多