Cú pháp
Quy tắc cơ bản
IndentationChỉ dùng spaces (không tab), độ sâu nhất quán
#Chú thích (đến cuối dòng)
---Marker bắt đầu tài liệu
...Marker kết thúc tài liệu
Case sensitiveKeys và values phân biệt hoa thường
Ví dụ tối giản
--- name: Alice age: 30 active: true
Scalars
Các loại Scalar
helloChuỗi (không dấu ngoặc)
"hello"Chuỗi (ngoặc kép, hỗ trợ escape)
'hello'Chuỗi (ngoặc đơn, literal)
42 / 3.14Số (nguyên / thực)
true / falseBoolean
null / ~Giá trị null
2026-03-26Ngày (ISO 8601)
Quy tắc dấu ngoặc
plain: no quotes needed special: "colon: and hash # need quotes" escape: "line\nnewline" literal: 'no \n escaping here'
Sequences
Block Sequence
fruits: - apple - banana - cherry
Flow Sequence (Inline)
colors: [red, green, blue] matrix: [[1, 2], [3, 4]]
Sequence các đối tượng
users: - name: Alice role: admin - name: Bob role: user
Mappings
Block Mapping
server: host: localhost port: 8080 debug: false
Flow Mapping (Inline)
point: {x: 10, y: 20}
Keys phức tạp
? [first, second] : "compound key value"
Anchors & Aliases
Định nghĩa & Tái sử dụng
defaults: &defaults timeout: 30 retries: 3 production: <<: *defaults timeout: 60
Tham chiếu
&nameĐịnh nghĩa anchor
*nameTham chiếu (alias) một anchor
<<Merge key — merge mapping vào hiện tại
Chuỗi nhiều dòng
Block Scalars
| (literal)Giữ nguyên các xuống dòng
> (folded)Gấp xuống dòng thành spaces
|+ (keep)Literal, giữ các xuống dòng cuối
|- (strip)Literal, bỏ các xuống dòng cuối
>- (fold+strip)Gấp, bỏ các xuống dòng cuối
Literal Block
script: | echo "line one" echo "line two"
Folded Block
description: > This long text will be folded into a single line with spaces.
Tags
Type Tags
!!str 42Ép giá trị thành chuỗi "42"
!!int "42"Ép giá trị thành số nguyên 42
!!float 1Ép giá trị thành số thực 1.0
!!bool "true"Ép giá trị thành boolean
!!null ""Ép giá trị thành null
!!binaryDữ liệu nhị phân mã hóa Base64
Ví dụ Tag
port: !!str 8080 enabled: !!bool "yes" version: !!float 3
Các mẫu thường dùng
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
Mẹo
yamllintLint YAML về cú pháp và phong cách
yqBộ xử lý YAML dòng lệnh (giống jq)
Avoid NorwayNO là boolean false — đặt mã quốc gia trong dấu ngoặc
Avoid !!pythonKhông bao giờ tải YAML không tin cậy với loader không an toàn