YAML cheatsheet Syntax

  • yaml file or document:

yaml document contains multiple lines of text with the following rules.

At a high level, yaml documents are interpreted as Map or dictionaries

  • The first line begins with ---
  • End of the document with ...
  • each line of text contains key and value pairs like a map.
  • key and values are separated by a colon (:) and space
  • use spaces instead of the tab for indentation

a simple key and value mapping

key: value

a simple key and complex value mapping

key:< key2
    key3: value1 < value

Key accepts strings value can be one of the following

  • Scalar types
  • sequence or collection type
  • nested collections

yaml indent/spaces

tab spaces (4 spaces) are not allowed and give an error

There are two types of syntaxes

  • Indented blocks
  • Inline blocks

Indented blocks syntax

Inline blocks use indentation or spaces for each line the new line is introduced to create a key and values

id: 1
name: Franc
salary: 5000

Inline blocks syntax

all the keys and value pairs are separated by a comma and declared in braces, value is separated by colon and spaces

{id:1,name: Franc,salary: 5000}

yaml datatypes

The following data types are supported by YAML:

TypesDescription
StringStrings are enclosed with or without double or single quotes
numberIt can be integers or floating values
BooleanAccepts true or false
sequenceSupports array or list
SetSet stores the elements unordered without duplicates
Mapmaps stores key with value as like hash map
binarysupport binary data of octal strings - images, files
timestampSupports date, DateTime

Scalars types - number, boolean, strings

Scalars are of integers or floating values, strings, Boolean values Strings can be enclosed in single double or unquoted

value:11
pivalue:3.14
isEnabled:false
strvalue1:'string value1'
strvalue2:"string value2"
strvalue3: string value3

Collection types

The following collections are supported

  • Sequence
  • Set
  • Nested Map or Dictionary

Sequence type

Sequences are like arrays or lists. Please see Sequence

Set

A Set is a list of unordered elements. It does not preserve duplicate elements.

Set stores the elements with null values

There are two types of syntax representation

typed sets using specifying !!set tag and ? symbol makes the set

numbers:!! set
? one
? two
? three

flow style sets It is json representation of values using !!set

numbers: !!set { 'one', "two", three }

the equivalent of the above two set examples a map

numbers:
  one: null
  two: null
  three: null

Dictionary or Nested Map

each line of the document and key and value pairs Each value can be nested with other documents using indentation. Using 2 spaces is a prerequisite, tabs are not supported

Employee:
  id: 1
  name: "Franc"
  department:
    name: "Sales"
    depid: "11"