YAML by Example: Key–Value Pairs
1.2
Basic mapping structure. Learn how to define data with keys and values.
Code
# Simple key-value pairs
name: John Doe
age: 30
city: New York
# Nested mappings
person:
first_name: Alice
last_name: Smith
contact:
email: [email protected]
phone: "+1-555-0123"
# Keys with special characters need quotes
"my-key": value
"key with spaces": another valueExplanation
YAML maps use a colon and space to separate keys from values. Keys are typically unquoted strings, but you need quotes if they contain special characters, start with numbers, or could be confused with YAML syntax. Values can be strings, numbers, or nested structures.
Nested mappings create hierarchy through indentation. Each nested level must be indented more than its parent, typically by 2 spaces. This structure maps directly to objects or dictionaries in most programming languages like JavaScript objects or Python dicts.
Code Breakdown
2
name: John Doe is a key-value pair with an unquoted string value.7
person: starts a nested mapping. Everything indented below belongs to it.
