📄 js-yaml/examples/sample_document

File: sample_document.md | Updated: 11/15/2025

Loading a YAML Document

This example demonstrates the basic usage of JS-YAML to load and parse a YAML document.

Overview

This is a simple example showing how to:

  • Read a YAML file from disk
  • Parse it using yaml.load()
  • Display the parsed JavaScript object

Code

'use strict';

var fs   = require('fs');
var path = require('path');
var util = require('util');
var yaml = require('../');

try {
  var filename = path.join(__dirname, 'sample_document.yml'),
      contents = fs.readFileSync(filename, 'utf8'),
      data     = yaml.load(contents);

  console.log(util.inspect(data, false, 10, true));
} catch (err) {
  console.log(err.stack || String(err));
}

Sample YAML Document

The example loads a comprehensive YAML document that demonstrates various YAML types and features:

---
# Collection Types

# Maps - Unordered key-value pairs
map:
  Block style: !!map
    Clark : Evans
    Ingy  : döt Net
    Oren  : Ben-Kiki
  Flow style: !!map { Clark: Evans, Ingy: döt Net, Oren: Ben-Kiki }

# Ordered maps
omap:
  Bestiary: !!omap
    - aardvark: African pig-like ant eater. Ugly.
    - anteater: South-American ant eater. Two species.
    - anaconda: South-American constrictor snake. Scaly.
  Numbers: !!omap [ one: 1, two: 2, three : 3 ]

# Pairs - Allow duplicate keys
pairs:
  Block tasks: !!pairs
    - meeting: with team.
    - meeting: with boss.
    - break: lunch.
    - meeting: with client.
  Flow tasks: !!pairs [ meeting: with team, meeting: with boss ]

# Sets - Unordered collection of unique values
set:
  baseball players: !!set
    ? Mark McGwire
    ? Sammy Sosa
    ? Ken Griffey
  baseball teams: !!set { Boston Red Sox, Detroit Tigers, New York Yankees }

# Sequences - Ordered lists
seq:
  Block style: !!seq
  - Mercury
  - Venus
  - Earth
  - Mars
  Flow style: !!seq [ Mercury, Venus, Earth, Mars ]

# Scalar Types

# Binary data
binary:
  canonical: !!binary "\
    R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5\
    OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+\
    +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC\
    AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs="

# Boolean values
bool:
  - true
  - True
  - TRUE
  - false
  - False
  - FALSE

# Float values
float:
  canonical: 6.8523015e+5
  exponential: 685.230_15e+03
  fixed: 685_230.15
  sexagesimal: 190:20:30.15
  negative infinity: -.inf
  not a number: .NaN

# Integer values
int:
  canonical: 685230
  decimal: +685_230
  octal: 02472256
  hexadecimal: 0x_0A_74_AE
  binary: 0b1010_0111_0100_1010_1110
  sexagesimal: 190:20:30

# Merge keys - For reusing map fragments
merge:
  - &CENTER { x: 1, y: 2 }
  - &LEFT { x: 0, y: 2 }
  - &BIG { r: 10 }
  - &SMALL { r: 1 }

  - # Merge one map
    << : *CENTER
    r: 10
    label: center

  - # Merge multiple maps
    << : [ *CENTER, *BIG ]
    label: center/big

# Null values
null:
  empty:
  canonical: ~
  english: null
  ~: null key
  sparse:
    - ~
    - 2nd entry
    -
    - 4th entry
    - Null

# String
string: abcd

# Timestamps
timestamp:
  canonical:        2001-12-15T02:59:43.1Z
  valid iso8601:    2001-12-14t21:59:43.10-05:00
  space separated:  2001-12-14 21:59:43.10 -5
  no time zone (Z): 2001-12-15 2:59:43.10
  date (00:00:00Z): 2002-12-14

What This Example Demonstrates

Collection Types

  • map: Unordered key-value pairs (JavaScript objects)
  • omap: Ordered maps that preserve insertion order
  • pairs: Lists of key-value pairs (allows duplicate keys)
  • set: Unordered collections of unique values
  • seq: Ordered sequences (JavaScript arrays)

Scalar Types

  • binary: Base64-encoded binary data
  • bool: Boolean values (multiple representations)
  • float: Floating-point numbers (various formats)
  • int: Integers (decimal, octal, hex, binary, sexagesimal)
  • merge: Anchors and aliases for reusing YAML fragments
  • null: Null values (multiple representations)
  • str: String values
  • timestamp: Date and time values

YAML Features

  • Both block and flow styles
  • Anchors (&) and aliases (*)
  • Merge keys (<<)
  • Comments
  • Multiple number formats (hexadecimal, octal, binary, sexagesimal)
  • Type tags (!!map, !!set, etc.)

Usage

node sample_document.js

This will output the parsed JavaScript object with proper indentation and colors (when run in a terminal that supports colors).

Key Functions

  • yaml.load(string): Parses a YAML string and returns a JavaScript object
  • util.inspect(object, options): Formats a JavaScript object for display

Error Handling

The example includes a try-catch block to handle potential errors:

  • File not found
  • Invalid YAML syntax
  • UTF-8 encoding issues

Related Examples

  • See custom_types.md for how to handle custom YAML tags
  • See dumper.md for how to convert JavaScript objects back to YAML