YAML Type Coercion: Unexpected Boolean and Number Parsing
Understand how YAML automatically converts values to booleans, numbers, and null. Learn the notorious 'Norway problem' and how to prevent unintended type coercion with quoting strategies.
Detailed Explanation
YAML Type Coercion
One of YAML's most controversial features is its aggressive automatic type detection. Unquoted values are parsed according to a set of rules that can produce surprising results, leading to bugs that are difficult to track down.
The Norway Problem
The most famous YAML type coercion issue:
countries:
- GB # String "GB"
- FR # String "FR"
- NO # Parsed as boolean false!
- DE # String "DE"
In YAML 1.1, NO is interpreted as boolean false because YAML recognizes many boolean literals: yes/no, true/false, on/off, y/n (case-insensitive).
Boolean Values in YAML 1.1
All of these are parsed as booleans:
| True values | False values |
|---|---|
true, True, TRUE |
false, False, FALSE |
yes, Yes, YES |
no, No, NO |
on, On, ON |
off, Off, OFF |
y, Y |
n, N |
YAML 1.2 limits booleans to only true and false, but many parsers still use YAML 1.1 rules.
Number Coercion
version: 1.0 # Float 1.0, not string "1.0"
build: 0123 # Octal number 83, not string "0123"
phone: 1-800-555 # String (not a valid number pattern)
port: 8080 # Integer 8080
price: 9.99 # Float 9.99
infinity: .inf # Infinity
not_a_number: .nan # NaN
Null Values
value: null # Null
value: ~ # Null
value: # Null (empty value)
value: Null # Null
value: NULL # Null
The Fix: Quote Your Strings
The safest approach is to quote any value that should remain a string:
countries:
- "GB"
- "FR"
- "NO" # Now correctly a string
- "DE"
version: "1.0" # String, not float
enabled: "yes" # String, not boolean
Formatter and Linter Rules
Modern YAML tools can help:
- yamllint has a
truthyrule that warns about unquoted boolean-like values - Some formatters offer an option to auto-quote ambiguous values
- JSON Schema validation can enforce string types for specific fields
Use Case
Type coercion bugs are among the most common YAML-related production incidents. A CI pipeline where 'on: push' is parsed as 'true: push', a country code list where NO becomes false, or a version number 1.0 that loses its decimal precision — all of these are real-world issues. Understanding type coercion is essential for anyone writing YAML configuration files.