YAML 101

YAML được sử dụng để viết ra các files cấu hình, sử dụng phổ biến trong nhiều dự án vì tính dễ đọc, đơn giản, linh hoạt, ví dụ như: Docker-compose, Kubernetes, Ansible, ...

Hiện nay có nhiều dạng Markup Languages như: YAML, JSON, XML, ... Mỗi loại markup language sẽ có vai trò riêng và được áp dụng vào từng mục đích cụ thể. Các markup languages giúp chúng ta dễ dàng lưu trữ thông tin, dễ tiếp cận & chia sẻ, dung lượng nhẹ để dễ truyền tải dữ liệu.

YAML Ain’t Markup Language (YAML) is a serialization language that has steadily increased in popularity over the last few years. It’s often used as a format for configuration files, but its object serialization abilities make it a viable replacement for languages like JSON. This YAML tutorial will demonstrate the language syntax with a guide and some simple coding examples in Python. YAML has broad language support and maps easily into native data structures. It’s also easy to for humans to read, which is why it’s a good choice for configuration.

YAML(Yet Another Markup language hay YAML Ain’t a MarkUp language) được sử dụng để viết ra các files cấu hình, sử dụng phổ biến trong nhiều dự án vì tính dễ đọc, đơn giản, linh hoạt, ví dụ như: Docker-compose, Kubernetes, Ansible, ...

YAML hỗ trợ mã hoá tất cả dữ liệu có cấu trúc, có thể dễ dàng viết & đọc hiểu.

Dưới đây, chúng ta có đoạn YAML  như sau:

---
# An employee record
name: Martin D'vloper
job: Developer
skill: Elite
employed: True
foods:
  - Apple
  - Orange
  - Strawberry
  - Mango
languages:
  perl: Elite
  python: Elite
  pascal: Lame
education: |
  4 GCSEs
  3 A-Levels
  BSc in the Internet of Things

Hiển thị dưới dạng JSON :

{
  "name": "Martin D'vloper",
  "job": "Developer",
  "skill": "Elite",
  "employed": true,
  "foods": [
    "Apple",
    "Orange",
    "Strawberry",
    "Mango"
  ],
  "languages": {
    "perl": "Elite",
    "python": "Elite",
    "pascal": "Lame"
  },
  "education": "4 GCSEs\n3 A-Levels\nBSc in the Internet of Things\n"
}

Hiển thị dưới dạng XML :

<name>Martin D'vloper</name>
<job>Developer</job>
<skill>Elite</skill>
<employed>true</employed>
<foods>Apple</foods>
<foods>Orange</foods>
<foods>Strawberry</foods>
<foods>Mango</foods>
<languages>
  <perl>Elite</perl>
  <python>Elite</python>
  <pascal>Lame</pascal>
</languages>
<education>4 GCSEs3 A-LevelsBSc in the Internet of Things</education>

YAML có nhiều điểm vượt trội. Bảng dưới đây so sánh giữa YAML và JSON

Attribute YAML JSON
Verbosity Less verbose More verbose
Data types Supports complex data types. Does not support complex data types.
Comments Supports writing Comments using "#". Doesn't support writing comments.
Readability More human-readable. Lesser human-readable.
Self-references Supports referencing elements within the same documents using "&," and *. Doesn't support self-referencing.
Multiple documents Supports multiple documents in a single file. Supports single document in a single file.

Tham khảo thêm tại đây

Để chuyển YAML  -> JSON chúng ta có thể sử dụng json2yaml

YAML Syntax

- Sử dụng Indentation để biểu thị cấu trúc dữ liệu.
- Chỉ dùng các kí tự khoảng trắng(space), không hỗ trợ tab.
- File YAML được lưu dưới dạng UTF-8 encoding.
- Khai báo YAML bắt đầu bằng --- và kết thúc với ... (điểu này ko bắt buộc).

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

Đảm bảo luôn có ít nhất một dấu cách(space) sau ký tự :khi khai báo giá trị , ví dụ: name: Joe is là syntax hợp lệ, còn name:Joe ko hợp lệ.
Các mục bên trong được thụt vào với hai khoảng trắng "  "

Ví dụ:

foo: bar
pleh: help
stuff:
  foo: bar
  bar: foo

Comments

Comments bắt đầu bằng #. Có thể khai báo sau value hoặc trên một dòng.

# This is a full line comment
foo: bar # this is a comment, too

Các kiểu data trong YAML

key: value là thành phẩn cơ bản xây dựng lên YAML, key luôn là một string, value có thể là bất kỳ kiểu dữ liệu nào(string, number, dictionary, ...).

Numeric types

YAML hỗ trợ nhiều kiểu numbers như: Integer, float, double, ...

 int: 12345
 hex: 0x12d4
 float: 1230.15
 exp: 12.3015e+05 # exponential floating point numbers
 infinity: .inf
 ninfinity: -.Inf # negative infinity
 nan: .NAN # not-a-number

Booleans

Một giá trị Boolean có thể là:

  • True/False
  • Yes/No
  • On/Off.
foo: True  
bar: False  
fan: On  
light: Off  

Strings

Đây là cách khai báo phổ biến, không cần thêm " ".

foo: this is a normal string
# foo: "this is a normal string"

Để chứa các ký tự đặc biệt (ký tự khác chữ và số): (:, {, }, [, ], ,, &, *, #, ?, |, -, <, >, =, !, %, @, \).

Chúng ta đặt chúng trong cặp dấu ngoặc kép " ".

foo: "this is not a normal string\n"

Multiline strings

Để khai báo giá trị có thể kéo dài nhiều dòng bằng cách sử dụng:

  • | (Literal style)
  • >(Folded style).

| : Sẽ lấy các kí tự newline(\n) và các khoảng trắng(trailing spaces).

bar: |
  this is not a normal string it
  spans more than
  one line
  see?

# => "bar": "this is not a normal string it\nspans more than\none line\nsee?\n"

>: Các kí tự newline (\n) sẽ được thay thành các khoảng trắng(spaces)

bar: >
  this is not a normal string it
  spans more than
  one line
  see?

# => "bar": "this is not a normal string it spans more than one line see?\n"

Sử dụng >- , |- : Loại bỏ các dòng trống ở cuối dòng

bar: >-
  this is not a normal string it
  spans more than
  one line
  see?
  
  
# => "bar": "this is not a normal string it spans more than one line see?"

Sử dụng >+ ,|+ : Giữ lại các dòng trống ở cuối dòng.

bar: >-
  this is not a normal string it
  spans more than
  one line
  see?
  
  
# => "bar": "this is not a normal string it spans more than one line see?\n\n"

Nulls

Dưới đây là 2 cách khai báo giá trị: null

foo: ~
bar: null

Arrays

Có thể khai báo mảng trên 1 dòng

items: [ 1, 2, 3, 4, 5 ]
names: [ "one", "two", "three", "four" ]

Khai báo mảng trên nhiều dòng, mỗi phần tử trong mảng được xác định bằng ký tự -(gạch ngang), sau đó là dấu cách.

items:
  - 1 
  - 2 
  - 3
  - 4 
  - 5 
names:
  - "one"
  - "two"
  - "three"
  - "four"

Kết quả biểu diễn dưới dạng JSON:

{
  "items":[1,2,3,4,5],
  "names":["one","two","three","four"]
}

Cách viết nhiều dòng hữu ích khi cần khai báo object phức tạp, ví du như:

items:
  - things:
      thing1: huey
      things2: dewey
      thing3: louie
  - other things:
      key: value

Biểu diễn dưới dạng JSON:

{
  "items":[
    {
      "things":{
        "thing1":"huey",
        "things2":"dewey",
        "thing3":"louie"
      }
    },
    {
      "other things":{
        "key":"value"
      }
    }
  ]
}

Dictionaries

Dictionaries hay hashes dùng để chứa cấu trúc dữ liệu phức tạp, nó là một tập hợp các cặp key: value, mỗi cặp key: value có thể được lồng vào nhau.

foo: { thing1: huey, thing2: louie, thing3: dewey }

Biểu diễn dưới dạng JSON:

{
  "foo":{
    "thing1":"huey",
    "thing2":"louie",
    "thing3":"dewey"
  }
}

Kiểu dictionary phức tạp.

# Employee records
- martin:
    name: Martin D'vloper
    job: Developer
    skills:
      - python
      - perl
      - pascal
- tabitha:
    name: Tabitha Bitumen
    job: Developer
    skills:
      - lisp
      - fortran
      - erlang

Biểu diễn dưới dạng JSON:

[
  {
    "martin": {
      "name": "Martin D'vloper",
      "job": "Developer",
      "skills": [
        "python",
        "perl",
        "pascal"
      ]
    }
  },
  {
    "tabitha": {
      "name": "Tabitha Bitumen",
      "job": "Developer",
      "skills": [
        "lisp",
        "fortran",
        "erlang"
      ]
    }
  }
]

Nâng cao:

Anchors

Sẽ có lúc cần tái sử dụng một thuộc tính nào đó, để tránh khai báo lặp lại(DRY), chúng ta sẽ sử dụng anchor.

  • Kí hiệu & để định nghĩa đặt tên cho một anchor.
  • Kí hiệu * để sử dụng anchor.

Ví dụ:, &anchor ở đây là một anchor, để sử dụng: *anchor

---
foo: &anchor
 K1: "One"
 K2: "Two"
bar: *anchor

Kết quả

{
  "foo": {
    "K1": "One",
    "K2": "Two"
  },
  "bar": {
    "K1": "One",
    "K2": "Two"
  }
}

Extend

Trong YAML chúng ta có thể sử dụng tính năng kế thừa với <<

---
foo: &anchor
  K1: "One"
  K2: "Two"

bar:
  <<: *anchor
  K2: "I Changed"
  K3: "Three"

Hiểu đơn giản thì: anchor sẽ được inject vào trong bar, sau đó sử dụng tính năng kế thừa

Kết quả

{
  "foo": {
    "K1": "One",
    "K2": "Two"
  },
  "bar": {
    "K1": "One",
    "K2": "I Changed",
    "K3": "Three"
  }
}

Ngoài ra, để tái sử dụng một số keys từ foo và inject vào bar

---
foo:
 <<: &anchor
   K1: "One"
 K2: "Two"

bar:
 <<: *anchor
 K3: "Three"

Kết quả

{
  "foo": {
    "K1": "One",
    "K2": "Two"
  },
  "bar": {
    "K1": "One",
    "K3": "Three"
  }
}

Reference:
    https://blog.daemonl.com/2016/02/yaml.html
    https://rollout.io/blog/yaml-tutorial-everything-you-need-get-started/
    https://stackoverflow.com/questions/3790454/how-do-i-break-a-string-over-multiple-lines
    

GO TOP

🎉 You've successfully subscribed to itplusX!
OK
]