如果列表变为空,则使用yq删除列表项和父节点



我有带示例值的字段。

EDIT:根级别上还有其他节点(fields的同级节点(也需要保留

  • 如果值为空,我想删除父列表项
  • 如果没有剩下的示例,我想删除整个examples节点
  • 这些例子可能有自己的其他领域,但我只想遵循上面的两条规则

输入

project: people_ages
fields:
first_name:
examples:
- value: Jon
comment: A very common name
last_name:
examples:
- value: ''
comment: Where is his last name?
age:
examples:
- value: 22
comment: Just got out of college
- value:
comment: Not sure about his age

所需输出

project: people_ages
fields:
first_name:
examples:
- value: Jon
comment: A very common name
last_name:
age:
examples:
- value: 22
comment: Just got out of college

使用yq-mikefarah/yq-的Go版本

您可以使用to_entries/from_entries内建与mapselect的组合

yq '.fields | to_entries | map(select(.value.examples[].value != "")) | 
map(select(.value.examples | length >0)) | from_entries' yaml

to_entries方法将对象转换为键值对,前缀分别为keyvaluefrom_entries则相反。在两者之间,应用了将包含.value的对象排除为空字符串的逻辑。当前面的转换完成时,我们现在在.examples级别排除,以考虑那些具有非零条目的对象。


根据添加到问题中的更新要求,保留其他字段并保持原始YAML结构不变,建议使用更新选择运算符|=

yq '.fields |= (to_entries | map(select(.value.examples[].value != "")) | 
map(select(.value.examples | length >0)) | from_entries)' yaml

最新更新