【问题标题】:Conditionally add properties to elements of array with yq (version 4)使用 yq 有条件地向数组元素添加属性(版本 4)
【发布时间】:2021-03-17 22:30:44
【问题描述】:

我有一个包含数组的 YAML 文档。我想使用来自 mikefarah 的 yq version 4 有条件地向该数组的元素添加属性。

这是一个示例 YAML 文档。

name: "My Pets"
pets:
- name: "cat"
  age: 8
- name: "dog"
  age: 3
- name: "mouse"
  age: 1

我想把它变成,

name: "My Pets"
pets:
- name: "cat"
  age: 8
  shots: cat.upToDate
- name: "dog"
  age: 3
  shots: dog.upToDate
- name: "mouse"
  age: 1
  shots: mouse.upToDate

我们将shots 属性添加到pets 的每个元素。 shots 的值应该是 name 的任何值,点,upToDate

我正在尝试这样的事情,

yq eval '.pets[] | select(.name == "cat").shots = "cat.upToDate"' test.yaml

但这会产生,

name: "cat"
age: 8
shots: cat.upToDate
name: "dog"
age: 3
name: "mouse"
age: 1

我需要保留整个原始 YAML 文档并插入 shots 属性。

这很接近,但缺少所有其他宠物。

yq eval '.pets = (.pets[] | select(.name == "cat").shots = "cats.upToDate")' test.yaml

它产生,

name: "My Pets"
pets:
  name: "cat"
  age: 8
  shots: cats.upToDate

我在想也许我们可以将宠物的名字存储在一个变量中并在以后引用它,但是 v4 今天对我来说是全新的。

我希望有一个单行,这样我就不必过滤.name。这个数组的元素少于 10 个,因此我可以轻松地硬编码名称并调用 yq 10 次。

有什么想法或建议吗?非常感谢,韦尔登

【问题讨论】:

  • 这真的很接近。如果cat 可以动态计算,这将起作用:yq eval '.pets = (.pets | .[].shots = "cat.upToDate")' test.yaml
  • 这更接近了,但它对每个 shots 值重复 catyq eval '.pets = (.pets | .[].shots = .[].name + ".upToDate")' test.yaml

标签: arrays yaml jq yq


【解决方案1】:

使用|=,例如像这样:

yq eval '.pets[] |= (.shots = (.name + ".upToDate"))' pets.yaml

【讨论】:

  • 啊,我明白了。这完美无缺。我忽略了文档的update 部分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-10
  • 2012-10-09
  • 2016-08-01
  • 2017-04-28
  • 2015-04-05
  • 2020-12-29
相关资源
最近更新 更多