YAML (YAML Ain't Markup Language) is a human-readable data serialization format. Proper formatting is crucial for creating clean, readable, and maintainable YAML files. This guide outlines key formatting guidelines to help you write effective YAML code.
Consistent indentation is vital in YAML. Use spaces for indentation, not tabs. The standard practice is to use 2 spaces per indentation level.
parent:
child1: value1
child2: value2
grandchild: value3
Use a colon and a space to separate keys from values. Ensure there's no space before the colon.
key: value
long_key: long value
Use hyphens followed by a space for list items. Indent list items consistently.
fruits:
- apple
- banana
- cherry
Use the hash symbol (#) for comments. Place comments on their own line or at the end of a line, preceded by at least one space.
# This is a comment
key: value # This is an inline comment
For multi-line strings, use the pipe symbol (|) for literal blocks or the greater-than symbol (>) for folded blocks.
literal_block: |
This is a
multi-line
string.
folded_block: >
This is another
multi-line string
that will be folded.
Use quotation marks for strings containing special characters or when you want to preserve specific formatting.
special_string: "This string: contains: colons"
preserve_spaces: " This string has leading spaces "
Be aware of YAML Version Compatibility when using advanced features. Stick to YAML 1.2 for maximum compatibility across different parsers.
Following these YAML formatting guidelines will help you create clean, readable, and maintainable configuration files. Consistent formatting enhances collaboration and reduces errors in your projects. For more advanced topics, explore YAML Complex Structures and YAML for App Configuration.