完整的YAML 1.2语法参考,附带示例。涵盖标量、序列、映射、锚点、多行字符串、标签和常见陷阱。
Plain unquoted string — most common
name: John Doe
Single-quoted: no variable or escape processing
path: '/usr/bin/node'
Double-quoted: supports escape sequences (\n, \t, etc.)
message: "Hello\nWorld"
Whole number (base 10)
port: 8080
Floating point number
threshold: 0.95
Boolean value — use only true/false (YAML 1.2)
debug: false
Null / absence of value
response: null
ISO 8601 date format
created: 2024-01-15T10:30:00Z
Single-line comment. No multi-line comment syntax.
# This is a comment key: value # inline comment
Force value to be treated as a specific type
port: !!str 8080 # string '8080' not int
Key-value pairs — indented block style
app: name: myapp port: 3000
Inline map — equivalent to block style
env: {NODE_ENV: prod, PORT: 8080}List of items — block style with dash+space
fruits: - apple - banana - cherry
Inline list — equivalent to block style
ports: [80, 443, 8080]
List where each item is a map
users:
- name: Alice
role: admin
- name: Bob
role: userArbitrarily deep nesting
database:
primary:
host: db1.example.com
port: 5432Merge the keys of a referenced mapping into current map
defaults: &defaults color: blue button: <<: *defaults text: Submit
Preserves newlines exactly as written
script: | #!/bin/bash echo "hello" exit 0
Newlines folded into spaces (great for long descriptions)
description: > This is a very long description that will be joined into one line.
Literal block, strip all trailing newlines
prompt: |- Enter value:
Literal block, keep all trailing newlines
template: |+ line1
Folded block, strip trailing newlines
message: >- This folds into one line no trailing newline
Assigns an anchor (label) to the current node
base: &base image: node:18 restart: always
References (copies) an anchored node
service1: <<: *base name: api service2: <<: *base name: worker
Anchor a scalar value to reuse it
read_timeout: &rto 30 write_timeout: *rto connect_timeout: *rto
Anchor a list
primary_colors: &colors - red - blue text_colors: *colors
Explicitly declare YAML version (optional, rarely needed)
%YAML 1.2 --- name: myapp
Marks the start of a YAML document. Required if using directives.
--- kind: Deployment --- kind: Service
Marks the end of a YAML document. Optional but useful.
--- debug: true ...
Multiple YAML docs in one file (stream)
Used in Kubernetes multi-resource files
Base64-encoded binary data
icon: !!binary | iVBORw0KGgo=
Indentation MUST use spaces only — never tabs
# WRONG: parent: \tchild: value # RIGHT: parent: child: value
Values containing ': ' (colon+space) must be quoted
# WRONG: url: http://example.com # RIGHT: url: "http://example.com"
1.0 parses as float! Quote or tag it to keep as string
version: '1.0' # string version: 1.0 # float
YAML 1.1 parses yes/no/on/off as booleans — quote to use strings
# YAML 1.1 (PyYAML): on: true # 'on' is boolean true! # Safe: always quote on: 'on'
Trailing spaces in keys are included in the key string
"key " (with space) != "key" — trim carefully
Duplicate keys — behavior is parser-specific (usually last wins). Treat as error.
Use a YAML linter to detect duplicate keys
| 特性 | YAML | JSON |
|---|---|---|
| 注释 | Yes: # comment | 不支持 |
| 需要引号 | 字符串可选 | 字符串必需 |
| Anchors/aliases | Yes: &anchor / *alias | 不支持 |
| 多行字符串 | Yes: | and > blocks | Escaped \n only |
| 缩进使用制表符 | 仅空格 | 均可 |
| 是JSON的超集 | 所有JSON都是有效的YAML | - |
| 人类可读性 | 非常高 | 中等 |
| 解析器可用性 | 高 | 非常高 |
重要: 许多YAML解析器默认仍使用YAML 1.1(Python的PyYAML、某些版本的Ruby的Psych)。
YAML是JSON的超集——任何有效的JSON都是有效的YAML。YAML旨在更易于人类阅读,支持注释、多行字符串和锚点/别名。JSON更严格、解析更快且被广泛支持。配置文件使用YAML,API和数据交换使用JSON。
在YAML 1.1(许多解析器包括PyYAML使用)中,'on'、'off'、'yes'、'no'是有效的布尔值。当作为普通字符串使用时(例如在Ansible中),这可能会导致错误。YAML 1.2修复了这个问题——只有'true'和'false'是布尔值。解决方法:如果要将这些值用作字符串,请始终加引号('yes'、'no')。
使用字面块标量(|)保留换行符:块中的每行成为字符串中的实际换行符。使用折叠块标量(>)将换行符折叠为空格:非常适合长段落。两者都支持可选的chomping指示符(- 删除尾部换行符,+ 保留所有换行符)。
YAML使用空格缩进——从不使用制表符。所有同级键必须在相同的缩进级别。混合使用制表符和空格总会导致错误。常见修复方法:在编辑器中启用「将制表符替换为空格」设置,使用linter(yamllint),确保整个文件使用一致的缩进宽度(2或4个空格)。