Skip to content
Search

YAML

lastmod 2025-02-12created 2015-10-1419 edits

YAML is a 'human-readable' data serialization format that draws its concepts from XML, C, Python, Perl, and the e-mail format defined in RFC2822. It was devised by Clark Evans in 2001 and designed together with Ingy dot Net and Oren Ben-Kiki.

The name YAML comes from the recursive name "YAML Ain't Markup Language”. Originally YAML meant “Yet Another Markup Language”, but the name was changed to show that YAML's core lies in data, not document markup. Today, as XML has begun to be used mainly for data serialization, many people are trying to use YAML as a 'lightweight markup language'.

What It Is: YAML is a human friendly data serialization standard for all programming languages.

Syntax

Start and end of a document

The start and end of a document are marked with --- and ... respectively.

---
# A list of tasty fruits
- Apple
- Orange
- Strawberry
- Mango
...

Basic

Parents and children are distinguished by indentation.

parent:
    child-1: first child
    child-2: 
        grandchild-1: first grand child
        grandchild-2: second grand child

Child nodes with the same parent must have exactly matching indentation. Otherwise it is an error.

Dictionary

Use key: value.

# An employee record
martin:
  name: Martin D'vloper
  job: Developer
  skill: Elite

List

"-" (a dash and a space):

---
# A list of tasty fruits
- Apple
- Orange
- Strawberry
- Mango
...

Flow collections

A #Dictionary can be written between { and } as follows.

martin: {name: Martin D'vloper, job: Developer, skill: Elite}

A #List can be written between [ and ] as follows.

fruits: ['Apple', 'Orange', 'Strawberry', 'Mango']

Boolean

create_key: true
needs_agent: false
knows_oop: True
likes_emacs: TRUE
uses_cvs: false

Use lowercase true or false for boolean values in dictionaries to stay compatible with the default yamllint options.

Multiple lines

Literal Block Scalar

Using | keeps newlines and trailing whitespace across multiple lines. Indentation is ignored.

include_newlines: |
            exactly as you see
            will appear these three
            lines of poetry

The value of 'include_newlines' is read as 'exactly as you see\nwill appear these three\nlines of poetry\n'.

Folded Block Scalar

Using > converts "newlines" into spaces across multiple lines. Indentation is ignored. It is used to make long lines easier to read and edit.

fold_newlines: >
            this is really a
            single line of text
            despite appearances

The value of 'fold_newlines' is read as 'this is really a single line of text despite appearances\n'.

Examples

List-Dict

key: 
  - child: 1
    name: tom
  - child: 2
    name: john

Parsing the above with pyyaml gives {'key': [{'child': 1, 'name': 'tom'}, {'child': 2, 'name': 'john'}]}.

Dict-Dict

key: 
    child-1: tom
    child-2: john

Parsing the above with pyyaml gives {'key': {'child-1': 'tom', 'child-2': 'john'}}.

Node

A node basically consists of a key: value pair. There are three kinds of items that can be the value.

# C 쪽의 POD 타입 비슷한 스칼라(scalar) : 문자열, 정수, 실수, 날짜 등등 여러 가지 타입이 들어갈 수 있다. 
key: value

# 시퀀스로 이루어진 자식 노드들. C 쪽의 배열(array)을 생각하면 된다. 정수형의 키를 가지는 노드라고 생각하면 쉽다. 
key: 
  - child: 1
    name: tom
  - child: 2
    name: john

# 매핑으로 이루어진 자식 노드들. 각 노드 간의 구분은 문자열로 이루어지며, 순서를 보장하지 않는다. 키 문자열을 이용해 정렬해 버리기 때문이다.
key: 
    child-1: tom
    child-2: john

Comment

Comments can only be written as lines starting with the # character. They cannot be placed next to a scalar value. If placed next to a scalar value, they are just treated as part of the string.1

# this is valid comment
key: 
  - child: 1   # !! WARNING: this is invalid comment !! <- 되는곳도 있고 안되는곳도 있는듯하다.
    name: tom
  - child: 2
    name: john

Alias

Repeated values can be reduced with anchors and aliases.

anchors:
    first-anchor: &first
        Name: tom
        Birth: 1977.4.21
# Anchor
    second-anchor: &second
        Name: john
        Birth: 1979.7.15

# Alias
first-child  : *first
second-child : *second

This way, when the program accesses the child node through the first-child key, the values under the first-anchor node are returned. It is easy to think of it like pointers in C.

Injection

Content that has already been defined can be injected elsewhere. Use <<: *변수명.

formatters:
  default: &default_formatter
    format: "%(asctime)s.%(msecs)03d %(process)d/%(thread)s %(name)s %(levelname)s %(message)s"
    datefmt: "%Y-%m-%d %H:%M:%S"
    style: "%"

  simple:
    format: "{levelname[0]} {asctime} {name} {message}"
    datefmt: "%Y%m%d %H%M%S"
    style: "{"

  color:
    <<: *default_formatter
    class: recc.log.colored_formatter.ColoredFormatter

Indentation caveats

If you do not indent after a list -, the line is treated as an object at the same Level. (In the example below, note that the value of literate-nav is null)

If you indent, it becomes a child object.

YAML

JSON

plugins:
  - literate-nav:
    nav_file: true
{
  "plugins": [
    {
      "nav_file": true, 
      "literate-nav": null
    }
  ]
}
plugins:
  - literate-nav:
      nav_file: true
{
  "plugins": [
    {
      "literate-nav": {
        "nav_file": true
      }
    }
  ]
}

In other words, you need to know exactly when whitespace is interpreted as null.

Implementation

See also

Favorite site

References


  1. Works fine in pyyaml ↩

  2. YAML_Spec_v1.2.pdf ↩

author Zer0 sitemap