You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用yq检测YAML中的块标量字符串与其他节点?

检测YAML节点类型(块标量字符串 vs 其他节点)

现有YAML文件内容

example0.yaml

quotation: |
"The true delight is in finding out rather than in the knowing" I. ASIMOV

example1.yaml

quotation: 
   Asimov: |
"The true delight is in finding out rather than in the knowing"

需求说明

通过Shell命令结合yq工具(支持Mike Farrah v4.31.2版本及Andrey Kislyuk版本),检测:

  • quotation0(对应example0.yaml的quotation节点)为块标量字符串
  • quotation1(对应example1.yaml的quotation节点)为其他类型节点

基于Mike Farrah yq v4.31.2的实现

该版本yq原生支持获取节点的类型标签和字符串样式,可直接判断块标量:

# 处理example0.yaml,检测quotation节点是否为块标量字符串
yaml0=$(cat example0.yaml)
quotation0_tag=$(echo "$yaml0" | yq '.quotation | tag')
quotation0_style=$(echo "$yaml0" | yq '.quotation | style')

if [ "$quotation0_tag" = "!!str" ] && [ "$quotation0_style" = "literal" ]; then
    echo "quotation0 是块标量字符串"
else
    echo "quotation0 不是块标量字符串"
fi

# 处理example1.yaml,检测quotation节点是否为非字符串类型
yaml1=$(cat example1.yaml)
quotation1_tag=$(echo "$yaml1" | yq '.quotation | tag')

if [ "$quotation1_tag" != "!!str" ]; then
    echo "quotation1 是其他类型节点(当前为映射节点)"
else
    echo "quotation1 是字符串节点"
fi

说明

  • tag操作符返回节点的YAML类型标签,块标量属于字符串类型,标签为!!str
  • style操作符返回字符串的定义样式,literal对应管道符|声明的块标量
  • example1.yaml的quotation是映射(对象)类型,标签为!!map,因此判定为其他节点

基于Andrey Kislyuk yq(python-yq)的实现

该版本基于jq,需结合原始YAML输出检测块标量特征:

# 处理example0.yaml,检测quotation节点是否为块标量字符串
yaml0=$(cat example0.yaml)
# 重新输出为YAML并检查块标量标记
is_block_scalar0=$(echo "$yaml0" | yq --yaml-output '.quotation' | grep -c '^|')
quotation0_type=$(echo "$yaml0" | yq '.quotation | type')

if [ "$quotation0_type" = "string" ] && [ "$is_block_scalar0" -gt 0 ]; then
    echo "quotation0 是块标量字符串"
else
    echo "quotation0 不是块标量字符串"
fi

# 处理example1.yaml,检测quotation节点类型
yaml1=$(cat example1.yaml)
quotation1_type=$(echo "$yaml1" | yq '.quotation | type')

if [ "$quotation1_type" != "string" ]; then
    echo "quotation1 是其他类型节点(当前为对象类型)"
else
    echo "quotation1 是字符串节点"
fi

说明

  • python-yq默认会将块标量解析为普通字符串,因此需要用--yaml-output将节点重新输出为YAML,再检查是否包含块标量的|标记
  • type操作符返回节点类型,example1.yaml的quotation是object类型,因此判定为其他节点

内容的提问来源于stack exchange,提问作者Lee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 08:47:25