YAML Line 5 Did Not Find Expected Key
Complete guide to fixing YAML syntax and parsing errors
Understanding the Error
YAML: line 5: did not find expected key
This error indicates that the YAML parser encountered a syntax issue at line 5. The parser expected to find a key-value pair but found something else instead. Common causes include incorrect indentation, missing colons, or invalid characters.
Common Causes
1. Incorrect Indentation
YAML is indentation-sensitive. Mixing tabs and spaces or inconsistent indentation causes errors.
Incorrect:
name: John
age: 30
city: New York
address: 123 Main St
Correct:
name: John
age: 30
city: New York
address: 123 Main St
2. Missing Colon
Keys must be followed by a colon and space before the value.
Incorrect:
name John
age 30
Correct:
name: John
age: 30
3. Invalid Characters in Keys
Keys containing special characters must be quoted.
Incorrect:
user-name: John
email@domain: test@example.com
Correct:
"user-name": John
"email@domain": test@example.com
4. Nested Structure Issues
Incorrect nesting of maps and lists causes parsing errors.
Incorrect:
person:
name: John
age: 30
Correct:
person:
name: John
age: 30
Step-by-Step Fix
Step 1: Check Line 5
Examine line 5 and the surrounding lines for syntax issues:
- Verify indentation matches the parent level
- Ensure there's a colon after the key
- Check for tabs mixed with spaces
- Look for special characters that need quoting
Step 2: Validate Indentation
YAML requires consistent indentation (typically 2 spaces):
# Use 2 spaces for each level
level1:
level2:
level3: value
Step 3: Use a YAML Validator
Validate your YAML file using online tools or command-line validators:
# Using Python
python -c "import yaml; yaml.safe_load(open('file.yaml'))"
# Using yamllint
yamllint file.yaml
# Online validator
# Use YAML.cc validator tool
Example: Fixing a Common Error
Problematic YAML (causes error at line 5):
apiVersion: v1
kind: ConfigMap
metadata:
name: my-config
data
key1: value1
key2: value2
Error: Missing colon after "data" on line 4, causing parser to fail at line 5
Fixed YAML:
apiVersion: v1
kind: ConfigMap
metadata:
name: my-config
data:
key1: value1
key2: value2
Solution: Added colon after "data" to properly define the key
Prevention Tips
-
•
Use spaces, not tabs - Configure your editor to show whitespace and convert tabs to spaces
-
•
Consistent indentation - Use 2 spaces per indentation level consistently
-
•
Validate before use - Run YAML through a validator before deploying or committing
-
•
Use YAML-aware editors - Editors like VS Code with YAML extensions provide real-time validation
-
•
Quote special keys - When in doubt, quote keys containing special characters