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

为何双空格缩进的YAML解析结果与四空格缩进的不同?

Why does Psych (Ruby 2.5) parse double-space indented YAML differently than four-space?

This behavior is completely compliant with the YAML 1.2 specification—the difference comes down to how YAML defines strict indentation rules for nested mappings and sequences. Let’s break this down clearly:

First, let’s clarify the actual structure of your YAML examples

Your double-space indented YAML (properly formatted with line breaks to show indentation levels) looks like this:

windows:
  - shell:
    panes:
      - echo hello

Your four-space indented version is:

windows:
  - shell:
      panes:
        - echo hello

The key YAML 1.2 rule driving this behavior

YAML requires that content nested under a mapping key (like shell:) must be indented beyond the starting column of the key itself.

Let’s break down the indentation columns to see the difference:

  • In the double-space case:
    • shell: starts at column 2 (after windows: and the sequence marker -).
    • panes: is also indented to column 2—aligned with the start of shell:. Since it’s not indented further, YAML treats panes: as a sibling key to shell:, not a child. That’s why shell ends up with a nil value (it has no nested content assigned to it) and panes becomes a separate key in the same array element.
  • In the four-space case:
    • panes: is indented to column 4—well beyond the start of shell: (column 2). This tells YAML that panes: is a child mapping under shell:, so shell correctly gets the value {"panes": ["echo hello"]} as you expected.

Why this rule exists

YAML relies entirely on indentation to define hierarchy (similar to Python). Requiring nested content to be indented past the parent key’s starting column eliminates ambiguity about which elements belong to which parent structure. Psych, Ruby’s default YAML parser, strictly enforces this rule.

Summary

Your double-space indent didn’t create the nesting you intended because panes: wasn’t indented far enough to be recognized as a child of shell:. The four-space version correctly signals the nested hierarchy, hence the expected parsing result.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:02:57