YAML 簡介

基本語法

  • Strings
# Strings don't require quotes:
title: Introduction to YAML

# But you can still use them:
title-w-quotes: 'Introduction to YAML'

# Multiline strings start with |
execute: |
    npm ci
    npm build
    npm test

// 轉成 JSON 就會像:
{
    "title": "Introduction to YAML",
    "title-w-quotes": "Introduction to YAML",
    "execute": "npm ci\nnpm build\nnpm test\n"
}
  • Numbers
# Integers:
age: 29

# Float:
price: 15.99

# Scientific notation:
population: 2.89e+6

// JSON
{
    "age": 29,
    "price": 15.99,
    "population": 2890000
}
  • Boolean
# Boolean values can be written in different ways:
published: false
published: False
published: FALSE
  • Null
# Null can be represented by simply not setting a value:
null-value: 

# Or more explicitly:
null-value: null
null-value: NULL
null-value: Null
  • Date & timestamps
date: 2002-12-14
canonical: 2001-12-15T02:59:43.1Z
iso8601: 2001-12-14t21:59:43.10-05:00
spaced: 2001-12-14 21:59:43.10 -5
  • Sequences
# A list of numbers using hyphens:
numbers:
    - one
    - two
    - three

# The inline version:
numbers: [ one, two, three ]
  • Nested values
# Nineteen eighty four novel data.
nineteen-eighty-four:
    author: George Orwell
    published-at: 1949-06-08
    page-count: 328
    description: |
        A Novel, often published as 1984, is a dystopian novel by English novelist George Orwell.
        It was published in June 1949 by Secker & Warburg as Orwell's ninth and final book.
  • List of objects
# Let's list books:
- nineteen-eighty-four:
    author: George Orwell
    published-at: 1949-06-08
    page-count: 328
    description: |
        A Novel, often published as 1984, is a dystopian novel by English novelist George Orwell.

- the-hobbit:
    author: J. R. R. Tolkien
    published-at: 1937-09-21
    page-count: 310
    description: | 
        The Hobbit, or There and Back Again is a children's fantasy novel by English author J. R. R. Tolkien.
  • Reusability with Node Anchors
# The author data:
author: &gOrwell 
    name: George
    last-name: Orwell

# Some books:
books: 
    - 1984:
        author: *gOrwell 
    - animal-farm:
        author: *gOrwell
  • Explicit data types with tags
# The following value should be an int, no matter what:
should-be-int: !!int 3.2

# Parse any value to string:
should-be-string: !!str 30.25

# I need the next value to be boolean:
should-be-boolean: !!bool yes

// JSON
{
    "should-be-int": 3,
    "should-be-string": "30.25",
    "should-be-boolean": true
}

參考資源