Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Complete Guide to YAML Configuration Syntax

Tech May 10 4

Introduction to YAML

YAML (YAML Ain't Markup Language) is a human-readable data serialization format designed for configuration files and data exchange. Unlike JSON, YAML emphasizes readability and offers a more concise syntax for representing complex data structures.

Basic Rules

  • Case-sensitive syntax
  • Hierarchy defined by indentation
  • Only spaces allowed for indentation (tabs are forbidden)
  • Alignment determines nesting level
  • Comments start with #

YAML supports three primary data types:

  • Mappings: Key-value pairs (objects/hashes/dictionaries)
  • Sequences: Ordered lists (arrays)
  • Scalars: Single atomic values

Mapping Syntax

Key-value pairs use a colon separator:

creature: feline

Parsed result:

{ creature: 'feline' }

Inline mapping notation:

user: { name: Alice, role: admin }

Parsed result:

{ user: { name: 'Alice', role: 'admin' } }

Sequence Syntax

List items begin with a hyphen:

- Lion
- Tiger
- Leopard

Parsed result:

[ 'Lion', 'Tiger', 'Leopard' ]

Nested sequences require indentation:

-
  - Lion
  - Tiger
  - Leopard

Parsed result:

[ [ 'Lion', 'Tiger', 'Leopard' ] ]

Inline array notation:

predators: [Lion, Tiger]

Parsed result:

{ predators: [ 'Lion', 'Tiger' ] }

Composite Structures

Mappings and sequences can be combined:

frameworks:
  - Django
  - Flask
  - FastAPI
endpoints:
  auth: /api/login
  data: /api/fetch
  users: /api/users

Parsed result:

{ frameworks: [ 'Django', 'Flask', 'FastAPI' ],
  endpoints: {
    auth: '/api/login',
    data: '/api/fetch',
    users: '/api/users'
  }
}

Scalar Types

YAML supports various scalar data types including strings, booleans, integers, floats, null values, timestamps, and dates.

Numeric values:

pi: 3.14159
count: 42

Boolean values:

enabled: true
disabled: false

Null values use tilde:

optional: ~

Timestamps in ISO8601 format:

created: 2023-06-15T14:30:00.00Z

Date values:

birthdate: 1990-12-25

Type coercion with double exclamation marks:

stringNum: !!str 456
stringBool: !!str false

Parsed result:

{ stringNum: '456', stringBool: 'false' }

String Handling

Strings without special characters need no quotes:

greeting: Hello World

Strings containing colons or special characters require quotes:

instruction: "Value: important"

Single quotes preserve literal characters:

literal: 'Line1\nLine2'

Double quotes interpret escape sequences:

escaped: "Line1\nLine2"

Single quote escaping within single quotes:

apostrophe: 'It''s working'

Multi-line strings fold into single line:

description: This is a
  multi-line
  text block

Literal block scalar preserves newlines with pipe:

content: |
  First line
  Second line
  Third line

Folded block scalar converts newlines to spaces:

summary: >
  This entire block
  becomes one line
  of text

Block chomping indicators:

clip: |
  Text
  
strip: |- 
  Text
  
keep: |+
  Text

Anchors and Aliases

Use anchors (&) and aliases (*) to reuse content:

default_settings: &defaults
  timeout: 30
  retries: 3

production:
  env: prod
  <<: *defaults

staging:
  env: stage
  <<: *defaults

The merge key (<<) inserts the anchored content. Equivalent expanded form:

production:
  env: prod
  timeout: 30
  retries: 3

Array element reuse:

- &lead Developer1
- Developer2
- Developer3
- *lead

Parsed result:

[ 'Developer1', 'Developer2', 'Developer3', 'Developer1' ]

JavaScript Function and Regex Serialization

JS-YAML can serialize JavaScript functions and regular expressions:

# config.yaml
handler: function () { return 42; }
pattern: /\d+/

Loading YAML in Node.js:

const yaml = require('js-yaml');
const fs = require('fs');

try {
  const data = yaml.load(fs.readFileSync('./config.yaml', 'utf8'));
  console.log(data);
} catch (err) {
  console.error(err);
}

Serializing objects back to YAML:

const yaml = require('js-yaml');
const fs = require('fs');

const config = {
  handler: function () { return 42; },
  pattern: /\d+/
};

try {
  fs.writeFileSync('./output.yaml', yaml.dump(config), 'utf8');
} catch (err) {
  console.error(err);
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.