📄 js-yaml/examples/dumper

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

YAML Dumper with Custom Styles

This example demonstrates how to dump JavaScript objects to YAML with custom formatting styles.

Overview

JS-YAML's dump() function allows you to customize the output format with options like:

  • flowLevel: Controls when to switch from block to flow style
  • styles: Specifies custom representation styles for specific YAML types

Input Data

{
  "name"      : "Wizzard",
  "level"     : 17,
  "sanity"    : null,
  "inventory" : [
    {
      "name"     : "Hat",
      "features" : [ "magic", "pointed" ],
      "traits"   : {}
    },
    {
      "name"     : "Staff",
      "features" : [],
      "traits"   : { "damage" : 10 }
    },
    {
      "name"     : "Cloak",
      "features" : [ "old" ],
      "traits"   : { "defence" : 0, "comfort" : 3 }
    }
  ]
}

Code

'use strict';

var yaml = require('../');
var object = require('./dumper.json');

console.log(yaml.dump(object, {
  flowLevel: 3,
  styles: {
    '!!int'  : 'hexadecimal',
    '!!null' : 'camelcase'
  }
}));

Options Explained

flowLevel

The flowLevel option determines at which nesting level to switch from block style to flow style:

  • flowLevel: 3 means that nodes at depth 3 and deeper will use flow style (inline format)
  • Flow style uses {} for objects and [] for arrays
  • Block style uses indentation

styles

The styles option lets you specify how to represent specific YAML types:

  • '!!int': 'hexadecimal' - Represents integers in hexadecimal format (e.g., 0x11 instead of 17)
  • '!!null': 'camelcase' - Represents null values as Null instead of null

Output

name: Wizzard
level: 0x11
sanity: Null
inventory:
  - name: Hat
    features: [magic, pointed]
    traits: {}
  - name: Staff
    features: []
    traits: {damage: 0xA}
  - name: Cloak
    features: [old]
    traits: {defence: 0x0, comfort: 0x3}

Available Style Options

For integers (!!int)

  • binary - Binary format (e.g., 0b1010)
  • octal - Octal format (e.g., 0o12)
  • decimal - Decimal format (default)
  • hexadecimal - Hexadecimal format (e.g., 0xA)

For null values (!!null)

  • lowercase - null
  • uppercase - NULL
  • camelcase - Null
  • ~ - Tilde representation

For strings (!!str)

  • plain - Unquoted
  • single - Single quotes
  • double - Double quotes
  • literal - Literal block scalar (|)
  • folded - Folded block scalar (>)

Use Cases

This is useful when you need to:

  • Generate YAML that matches a specific style guide
  • Create more readable YAML for nested structures
  • Represent numbers in specific formats (hex, binary, etc.)
  • Control the visual appearance of your YAML output