object - 将几个对象与 jq slurp 合并在一起而不覆盖重复键

标签 object ubuntu jq slurp

我有这两个 json 文件:
ubuntubionic.json :

  {
    "ubuntu": {
      "os_ver": "bionic",
      "image": "abcdef",
      "image_tag": "3.33.3",
      "docker_compiler_image": "abc",
      "image_compiler_tag": "4.44.4"
    }
  }
ubuntufocal.json :
cat ubuntubionic.json
  {
    "ubuntu": {
      "os_ver": "focal",
      "image": "xxxx",
      "image_tag": "3.33.3",
      "docker_compiler_image": "xxxx",
      "image_compiler_tag": "4.44.4"
    }
  }`
我想将这两个文件合并为 1 个文件以获得如下所示的输出:
{
    "ubuntu": {
      "os_ver": "focal",
      "image": "abcdef",
      "image_tag": "3.33.3",
      "docker_compiler_image": "abc",
      "image_compiler_tag": "4.44.4"
    },
      "os_ver": "bionic",
      "image": "xxxx",
      "image_tag": "3.33.3",
      "docker_compiler_image": "xxxx",
      "image_compiler_tag": "4.44.4"

  }
我试过 jq -s 添加 ubuntufocal.json ubuntubionic.json > all_os.json
但我知道仿生正在覆盖焦点
cat all_os.json
{
  "ubuntu": {
    "os_ver": "bionic",
    "image": "xxxx",
    "image_tag": "3.33.3",
    "docker_compiler_image": "xxxx",
    "image_compiler_tag": "4.44.4"
  }
}
如何解决?完全迷失在 JQ 手册页中

最佳答案

要使其成为文件内容的数组,您不需要 add内置为 -s flag 已经将它们放在一个数组中

jq -s . ubuntubionic.json ubuntufocal.json
[
  {
    "ubuntu": {
      "os_ver": "bionic",
      "image": "abcdef",
      "image_tag": "3.33.3",
      "docker_compiler_image": "abc",
      "image_compiler_tag": "4.44.4"
    }
  },
  {
    "ubuntu": {
      "os_ver": "focal",
      "image": "xxxx",
      "image_tag": "3.33.3",
      "docker_compiler_image": "xxxx",
      "image_compiler_tag": "4.44.4"
    }
  }
]
如果要拔出ubuntu字段名称,并将每个对象的值(恰好也是对象)合并到一个数组中,也使用 map内置:
jq -s '{ubuntu: map(.ubuntu)}' ubuntubionic.json ubuntufocal.json
或者
jq -s '{ubuntu: map(add)}' ubuntubionic.json ubuntufocal.json
{
  "ubuntu": [
    {
      "os_ver": "bionic",
      "image": "abcdef",
      "image_tag": "3.33.3",
      "docker_compiler_image": "abc",
      "image_compiler_tag": "4.44.4"
    },
    {
      "os_ver": "focal",
      "image": "xxxx",
      "image_tag": "3.33.3",
      "docker_compiler_image": "xxxx",
      "image_compiler_tag": "4.44.4"
    }
  ]
}

关于object - 将几个对象与 jq slurp 合并在一起而不覆盖重复键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70631402/

相关文章:

r - S3中的美元建议方法

linux - 从 Ubuntu 18.04 升级到 18.10 后,出现 Sendmail-Base 错误

linux - 让 RabbitMQ 自动运行?

ios - 核心数据发送和接收对象

JavaScript OOP Object.create();

javascript - 在 JavaScript 中将链接附加到头部时使用方括号 [ ]

c - 如何在 Ubuntu 的默认文件夹之外编译 ffmpeg 示例?

json - 对一个 JSON 模板进行多项更改

python - 使用jq正确解析数据

json - 解析错误 : Invalid numeric literal at line 1, 第 2 列 (bash)