我有这两个 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/