为何双空格缩进的YAML解析结果与四空格缩进的不同?
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 (afterwindows:and the sequence marker-).panes:is also indented to column 2—aligned with the start ofshell:. Since it’s not indented further, YAML treatspanes:as a sibling key toshell:, not a child. That’s whyshellends up with anilvalue (it has no nested content assigned to it) andpanesbecomes a separate key in the same array element.
- In the four-space case:
panes:is indented to column 4—well beyond the start ofshell:(column 2). This tells YAML thatpanes:is a child mapping undershell:, soshellcorrectly 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

