예제와 함께하는 완전한 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개) 유지.