YAML 快速参考
标量、序列、映射、锚点、多行字符串
语法
基本规则
| Indentation | 只用空格(不用 tab),缩进深度须一致 |
| # | 注释(到行尾) |
| --- | 文档开始标记 |
| ... | 文档结束标记 |
| Case sensitive | 键和值区分大小写 |
最小示例
---
name: Alice
age: 30
active: true
标量
标量类型
| hello | 字符串(无引号) |
| "hello" | 字符串(双引号,支持转义) |
| 'hello' | 字符串(单引号,字面值) |
| 42 / 3.14 | 数字(整数/浮点数) |
| true / false | 布尔值 |
| null / ~ | 空值 |
| 2026-03-26 | 日期(ISO 8601) |
引号规则
plain: no quotes needed
special: "colon: and hash # need quotes"
escape: "line\nnewline"
literal: 'no \n escaping here'
序列
块序列
fruits:
- apple
- banana
- cherry
流序列(内联)
colors: [red, green, blue]
matrix: [[1, 2], [3, 4]]
对象序列
users:
- name: Alice
role: admin
- name: Bob
role: user
映射
块映射
server:
host: localhost
port: 8080
debug: false
流映射(内联)
point: {x: 10, y: 20}
复合键
? [first, second]
: "compound key value"
锚点与别名
定义与复用
defaults: &defaults
timeout: 30
retries: 3
production:
<<: *defaults
timeout: 60
参考
| &name | 定义锚点 |
| *name | 引用(别名)锚点 |
| << | 合并键 — 将映射合并到当前 |
多行字符串
块标量
| | (literal) | 保留换行符 |
| > (folded) | 将换行折叠为空格 |
| |+ (keep) | 字面值,保留末尾换行 |
| |- (strip) | 字面值,去除末尾换行 |
| >- (fold+strip) | 折叠,去除末尾换行 |
字面块
script: |
echo "line one"
echo "line two"
折叠块
description: >
This long text will be
folded into a single line
with spaces.
类型标签
类型标签
| !!str 42 | 强制为字符串 "42" |
| !!int "42" | 强制为整数 42 |
| !!float 1 | 强制为浮点数 1.0 |
| !!bool "true" | 强制为布尔值 |
| !!null "" | 强制为空值 |
| !!binary | Base64 编码的二进制数据 |
标签示例
port: !!str 8080
enabled: !!bool "yes"
version: !!float 3
常用模式
Docker Compose
services:
web:
image: nginx:alpine
ports: ["80:80"]
environment:
NODE_ENV: production
GitHub Actions
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
技巧
| yamllint | YAML 语法与风格检查工具 |
| yq | 命令行 YAML 处理器(类似 jq) |
| Avoid Norway | NO 会被解析为布尔 false — 国家代码需加引号 |
| Avoid !!python | 不要用不安全的 loader 加载不可信的 YAML |