YAML Syntax and Usage Explained

1. Basic Definition

YAML is a human-readable data serialization format (recursive acronym: originally “Yet Another Markup Language”, later revised to “YAML Ain’t Markup Language” to emphasize it is not a markup language but a data format). It is designed to be easy for both humans to write/read and machines to parse/generate, commonly used for configuration files, data exchange between different programming languages, and defining structured data. Unlike JSON (more compact but less readable) or XML (verbose), YAML balances readability and structure, making it a mainstream choice for modern software configuration (e.g., Kubernetes, Ansible, Docker Compose).

2. Core Syntax Rules

YAML has strict but intuitive syntax rules, with the following key points:

2.1 Basic Structure

  • Key-Value Pairs: The core building block, formatted as key: value (note the space after the colon is mandatory).yamlname: John Doe age: 30 is_student: false
  • Indentation: Uses spaces (2 spaces recommended) to represent hierarchy (tabs are not allowed).yamlperson: name: John Doe contact: email: john@example.com phone: 123456789
  • Lists/Arrays: Defined with a hyphen (-) followed by a space, or square brackets [] (inline format).yaml# Line-by-line list fruits: - apple - banana - orange # Inline list numbers: [1, 2, 3, 4]
  • Nested Structures: Combine key-value pairs and lists for complex data.yamlemployees: - name: Alice department: Engineering skills: [Python, YAML, Kubernetes] - name: Bob department: Marketing skills: - SEO - Content Writing

2.2 Data Types

YAML supports common data types natively (no need for explicit type declaration):

TypeExampleNotes
Stringgreeting: "Hello World" or greeting: Hello WorldQuotes are optional (required for strings with special characters like :#).
Numberage: 30pi: 3.14159Integers and floats are auto-recognized.
Booleanis_active: trueis_deleted: falseCase-sensitive (only true/false are valid, not True/False).
Nullmiddle_name: null or middle_name: ~Both null and ~ represent empty values.
Date/Timebirthday: 1993-05-15login_time: 2025-12-04T10:30:00ZFollows ISO 8601 standard.

2.3 Advanced Features

  • Comments: Start with # (only line comments are supported, no block comments).yaml# This is a comment name: John # Comment after a key-value pair
  • Anchors & Aliases: Reuse data with & (anchor) and * (alias) to avoid duplication.yamlbase_config: &base timeout: 30 retries: 3 dev_config: <<: *base # Merge base config environment: development prod_config: <<: *base environment: production retries: 5 # Override base value
  • Multi-line Strings: Use | (preserve newlines) or > (fold newlines into spaces).yaml# Preserve newlines description: | This is a multi-line string. Each line is kept as-is. Including newlines. # Fold newlines summary: > This is a folded multi-line string. All newlines are converted to spaces, making it a single line.

3. Key Characteristics

  • Human-Friendly: Minimal syntax, no closing tags (unlike XML) or commas (unlike JSON), easy to read/write.
  • Language-Agnostic: Supported by almost all programming languages (Python, Java, Go, JavaScript, etc.) via dedicated libraries (e.g., PyYAML for Python, snakeyaml for Java).
  • Strict Typing: Automatically parses data types (avoids the “all strings” issue in some config formats).
  • Extensible: Supports custom tags (e.g., !timestamp 2025-12-04) for advanced type handling (though rarely used in basic configs).
  • Common Pitfalls: Indentation errors (most frequent issue), missing spaces after colons, mixing tabs/spaces, case sensitivity for booleans/null.

4. Typical Application Scenarios

  • Configuration Files: Kubernetes manifests (*.yaml), Ansible playbooks, Docker Compose files, GitHub Actions workflows, Python project pyproject.toml (YAML subset).
  • Data Serialization: Exchange structured data between different systems (e.g., API responses, data exports).
  • Infrastructure as Code (IaC): Define cloud resources (AWS CloudFormation, Terraform variables) in YAML for readability.
  • Application Settings: Replace JSON/INI files for app config (e.g., Flask/Django app config, CI/CD pipeline configs).

5. Comparison with JSON/XML

FeatureYAMLJSONXML
ReadabilityExcellent (human-friendly)Good (compact but less readable)Poor (verbose, tag-heavy)
Syntax ComplexityLow (minimal punctuation)Medium (commas, braces)High (tags, closing elements)
Data TypesRich (dates, booleans, null)Basic (strings, numbers, bool, null)None (all strings by default)
Use CaseConfiguration filesAPI data exchangeLegacy systems, SOAP APIs
IndentationRequired (spaces only)Optional (ignored)Optional (ignored)



了解 Ruigu Electronic 的更多信息

订阅后即可通过电子邮件收到最新文章。

Posted in

Leave a comment