0

i have this two json files: ubuntubionic.json:

  {
    "ubuntu": {
      "os_ver": "bionic",
      "image": "abcdef",
      "image_tag": "3.33.3",
      "docker_compiler_image": "abc",
      "image_compiler_tag": "4.44.4"
    }
  }

and 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"
    }
  }`

i want to merge these two files into 1 file to get output that looks like this:

{
    "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"

  }

i tried jq -s add ubuntufocal.json ubuntubionic.json > all_os.json but i'm getting that bionic is overwriting focal

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

how can this be solved? got totally lost in the JQ man page

4

1 回答 1

0

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

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"
    }
  ]
}
于 2022-01-08T10:51:16.520 回答