英文:
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 '[{"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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论