Start Coding

YAML Formatting Guidelines

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.

Indentation

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

Key-Value Pairs

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

Lists

Use hyphens followed by a space for list items. Indent list items consistently.


fruits:
  - apple
  - banana
  - cherry

Comments

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

Multi-line Strings

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.

Quotation Marks

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  "

Best Practices

  • Keep your YAML files organized and well-structured.
  • Use meaningful key names that accurately describe the data.
  • Avoid deep nesting; aim for a maximum of 3-4 levels when possible.
  • Use YAML Anchors and YAML Aliases to reduce repetition.
  • Validate your YAML using YAML Online Validators to catch syntax errors.

Version Compatibility

Be aware of YAML Version Compatibility when using advanced features. Stick to YAML 1.2 for maximum compatibility across different parsers.

Conclusion

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.