Skip to content

YAML

YAML은 XML, C, 파이썬, 펄, RFC2822에서 정의된 e-mail 양식에서 개념을 얻어 만들어진 '사람이 쉽게 읽을 수 있는' 데이터 직렬화 양식이다. 2001년에 클라크 에반스가 고안했고, Ingy dot Net 및 Oren Ben-Kiki와 함께 디자인했다.

YAML이라는 이름은 "YAML은 마크업 언어가 아니다 (YAML Ain't Markup Language)” 라는 재귀적인 이름에서 유래되었다. 원래 YAML의 뜻은 “또 다른 마크업 언어 (Yet Another Markup Language)”였으나, YAML의 핵심은 문서 마크업이 아닌 데이터 중심에 있다는 것을 보여주기 위해 이름을 바꾸었다. 오늘날 XML이 데이터 직렬화에 주로 쓰이기 시작하면서, 많은 사람들이 YAML을 '가벼운 마크업 언어'로 사용하려 하고 있다.

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

Syntax

문서의 시작과 끝

문서의 시작과 끝은 각각 ---...를 사용한다.

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

Basic

부모 자식의 구분은 들여쓰기를 통해 이루어진다.

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

같은 부모를 가지는 자식 노드들은 들여쓰기가 정확히 일치해야 한다. 틀리면 에러다.

Dictionary

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

#Dictionary는 다음과 같이 {} 사이에 표현할 수 있다.

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

#List는 다음과 같이 [] 사이에 표현할 수 있다.

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

Boolean

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

기본 yamllint 옵션과 호환되도록 하려면 사전의 부울 값에 소문자 true 또는 false를 사용하십시오.

Multiple lines

Literal Block Scalar

|를 사용하면 여러 줄에 걸쳐 줄 바꿈후행 공백이 포함됩니다. 들여쓰기는 무시됩니다.

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

'include_newlines'의 값은 'exactly as you see\nwill appear these three\nlines of poetry\n'로 읽혀진다.

Folded Block Scalar

>를 사용하면 여러 줄에 걸쳐 "개행"을 공백으로 변환합니다. 들여쓰기는 무시됩니다. 길 줄을 더 쉽게 읽고 편집할 수 있도록 만드는데 사용됩니다.

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

'fold_newlines'의 값은 'this is really a single line of text despite appearances\n'로 읽혀진다.

Examples

List-Dict

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

위는 pyyaml로 파싱하면 {'key': [{'child': 1, 'name': 'tom'}, {'child': 2, 'name': 'john'}]}가 된다.

Dict-Dict

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

위는 pyyaml로 파싱하면 {'key': {'child-1': 'tom', 'child-2': 'john'}}가 된다.

Node

하나의 노드는 기본적으로 key: value의 페어로 이루어진다. value에 해당하는 항목에는 3가지가 있다.

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

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

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

Comment

주석은 # 문자로 시작하는 라인으로만 달 수 있다. 스칼라 값 옆에다 달 수는 없다. 스칼라 값 옆에다 다는 경우 그냥 문자열로 취급한다.1

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

Alias

반복되는 값은 앵커 및 알리아스를 통해 줄일 수 있다.

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

이렇게 하면 프로그램 상에서 first-child 키를 통해 자식 노드를 접근하면 first-anchor 노드 아래에 있는 값들이 나오게 된다. C 쪽의 포인터를 생각하면 쉽다.

주입

이미 지정된 내용을 다른 곳에 주입할 수 있다. <<: *변수명를 사용하면 된다.

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

들여쓰기 주의점

리스트 - 사용 후 들어쓰기 안하면 동일 Level 의 객체로 판단한다. (아래의 예제에서 literate-nav의 값이 null 임을 확인)

들여쓰기 하면 하위 객체로 들어간다.

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
      }
    }
  ]
}

즉, 공백은 null 로 판단하게 되는지를 정확히 알아야 한다.

Implementation

See also

Favorite site

References


  1. pyyaml에서는 잘 되더라 

  2. YAML_Spec_v1.2.pdf