YQ:将简单的YAML对象展开为对象数组

huangapple go评论66阅读模式
英文:

YQ: explode simple YAML object into array of objects

问题

我正在使用Bash和YQ进行一些YAML解析。我的输入是一个包含两个数组属性的简单对象。我想要"explode"这两个数组,使我的简单对象转换为一个对象数组。

考虑以下YAML:

name: a
spaces:
  - alpha
  - beta
envs:
  - dev
  - test
  - prod

现在我想要"explode"这两个数组,使我得到多个对象:

- name: a
  space: alpha
  env: dev
- name: a
  space: alpha
  env: test
- name: a
  space: alpha
  env: prod
- name: a
  space: beta
  env: dev
- name: a
  space: beta
  env: test
- name: a
  space: beta
  env: prod

我该如何使用YQ实现这个?

英文:

I'm using Bash and <a href="https://github.com/mikefarah/yq">YQ</a> to do some YAML parsing. My input is a simple object that contains two array properties. I would like to explode both arrays so my simple object is converted into an array of objects.

Consider the following YAML:

name: a
spaces:
  - alpha
  - beta
envs:
  - dev
  - test
  - prod

Now I would like to "explode" both arrays so I get multiple objects:

- name: a
  space: alpha
  env: dev
- name: a
  space: alpha
  env: test
- name: a
  space: alpha
  env: prod
- name: a
  space: beta
  env: dev
- name: a
  space: beta
  env: test
- name: a
  space: beta
  env: prod

How can I do this with <a href="https://github.com/mikefarah/yq">YQ</a>?

答案1

得分: 2

只需使用 [] 迭代数组,使用 {…} 创建最终对象,并再次用数组括号 […] 包装所有内容:

yq '[{"name": .name, "space": .spaces[], "env": .envs[]}]' file.yaml
- name: a
  space: alpha
  env: dev
- name: a
  space: alpha
  env: test
- name: a
  space: alpha
  env: prod
- name: a
  space: beta
  env: dev
- name: a
  space: beta
  env: test
- name: a
  space: beta
  env: prod
英文:

Just iterate over the arrays using [], create your final objects using {…}, and wrap everthing in array brackets […] again:

yq &#39;[{&quot;name&quot;: .name, &quot;space&quot;: .spaces[], &quot;env&quot;: .envs[]}]&#39; file.yaml
- name: a
  space: alpha
  env: dev
- name: a
  space: alpha
  env: test
- name: a
  space: alpha
  env: prod
- name: a
  space: beta
  env: dev
- name: a
  space: beta
  env: test
- name: a
  space: beta
  env: prod

huangapple
  • 本文由 发表于 2023年2月8日 16:14:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75382917.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定