【问题标题】:Using jq to add/prepend an element to the top of an array使用 jq 在数组顶部添加/添加元素
【发布时间】:2021-03-31 23:29:42
【问题描述】:

我有以下 json 文件(example.json):

{
  "examples": [
    {
      "example": "2"
    },
    {
      "example": "3"
    }
  ]
}

我想使用 jq 在这个数组的顶部(而不是底部)添加一个新元素。我提出的所有解决方案只需将其添加到底部(我在下面使用的代码):

jq '.examples +=
[{"example": "1",
}]' example.json

所需的输出(如果不是很明显)将是:

{
  "examples": [
    {
      "example": "1"
    },
    {
      "example": "2"
    },
    {
      "example": "3"
    }
  ]
}

【问题讨论】:

    标签: arrays jq prepend


    【解决方案1】:

    您可以将数组与+ 连接起来,这样您就可以将新对象添加到数组中并连接其余对象:

    .examples |= [{example: "1"}] + .
    

    https://jqplay.org/s/XIsoZ4GvOa

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-14
      • 2021-08-14
      • 2017-07-03
      • 1970-01-01
      • 2022-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多