YAML supports multiple data types, and understanding these types is crucial for correctly writing and parsing YAML files.
YAML Data Type Classification
1. Scalar Types
Strings
- Plain strings: No quotes needed
- Quoted strings: Single or double quotes
- Multi-line strings: Use
|or>
yaml# Plain string name: John Doe # Single-quoted string (no escape for special characters) message: 'Hello\nWorld' # Double-quoted string (escape special characters) greeting: "Hello\nWorld" # Multi-line string (preserve line breaks) description: | This is a multi-line string # Multi-line string (fold line breaks) summary: > This is a folded string that becomes one line
Numbers
- Integers: Decimal, octal (0o), hexadecimal (0x)
- Floats: Support scientific notation
yamlinteger: 42 octal: 0o52 hex: 0x2A float: 3.14 scientific: 1.23e4 negative: -42
Booleans
- Multiple representations supported
yamltrue_value: true false_value: false yes: yes no: no on: on off: off
Null
- Multiple representations
yamlempty: null none: ~ empty2:
2. Collection Types
Lists/Arrays
- Represented with hyphen
- - Inline notation supported
yaml# Standard list fruits: - apple - banana - orange # Inline list colors: [red, green, blue] # Nested list matrix: - [1, 2, 3] - [4, 5, 6] - [7, 8, 9]
Maps/Dictionaries
- Represented with key-value pairs
- Inline notation supported
yaml# Standard map person: name: Alice age: 30 city: Beijing # Inline map config: {host: localhost, port: 8080} # Nested map server: database: host: db.example.com port: 5432 cache: type: redis ttl: 3600
3. Complex Types
Mixed Types (Combining Lists and Maps)
yamlusers: - name: Bob age: 25 skills: [Python, JavaScript] - name: Carol age: 28 skills: [Java, Go]
Custom Types
yaml# Use !! tag to specify type timestamp: !!timestamp 2024-01-01T00:00:00Z binary: !!binary | SGVsbG8gV29ybGQ=
Type Inference Rules
YAML parsers automatically infer types based on value format:
- Numbers: Pure numeric sequences
- Booleans: true/false, yes/no, on/off
- Null: null, ~, empty string
- Strings: All other cases
Type Conversion Techniques
Force Type Specification
yaml# Use quotes to force string port: "8080" # String, not number # Use !! tag to specify type age: !!int "25" # Force convert to integer
Special Character Handling
yaml# Strings with special characters need quotes path: "/usr/local/bin" regex: "\\d+"
Common Errors
- Type confusion: Expecting string but getting number
- Boolean misinterpretation: yes/no interpreted as booleans
- Date format: Some date formats auto-converted to timestamps
- Improper quote usage: Causing escape characters to fail
Best Practices
- Use quotes for values that explicitly need to be strings
- Use explicit type annotations for configuration items
- Avoid using yes/no as string values
- Use YAML Schema for type validation
- Maintain type consistency, don't mix different representations