完整的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個空格)。