如何使用yq v4移除所有包含'type: array'键值对的父节点
如何使用yq v4移除所有包含'type: array'键值对的父节点
我来帮你搞定这个问题!你想要删除的是components.schemas下那些直接包含type: array的顶层节点(比如例子里的pets),你的思路方向是对的,但语法上需要调整下。
正确的yq命令
直接用这个命令就能达到你想要的效果:
yq 'del(.components.schemas[] | select(.type == "array"))' filename.yaml
命令解释
让我拆解下这个命令的作用:
.components.schemas[]:遍历schemas下的所有子节点(也就是pets、pet这些键对应的值)select(.type == "array"):筛选出那些type字段等于"array"的节点del(...):删除这些被筛选出来的节点,对应的父键(比如pets)就会被一并移除
验证效果
运行命令前的原始YAML:
info: title: My API components: schemas: pets: type: array items: $ref: "#/components/schemas/pet" pet: type: object properties: petName: type: string
运行命令后的结果:
info: title: My API components: schemas: pet: type: object properties: petName: type: string
为什么你的之前命令没生效?
你之前写的yq 'del(.components.schemas.[] | select(. == "array") | parent)' filename.yaml有两个问题:
select(. == "array")这里的.代表整个节点的内容,而不是type字段,所以永远匹配不到- 其实不需要额外调用
parent,因为我们遍历的就是schemas下的子节点本身,直接删除选中的节点就会移除对应的父键
如果需要全局删除所有包含type: array的父节点(不局限于schemas下),可以用递归遍历的方式:
yq 'del(.. | select(has("type") and .type == "array"))' filename.yaml
备注:内容来源于stack exchange,提问作者Arjen
相关产品推荐
相关产品推荐

