YAML语法简介

YAML的数据结构

YAML的设计者认为在配置文件中所要表达的数据内容有三种类型

  • Scalars(标量,如字符串和数字等)
  • Sequence (序列,类似于Python中列表的概念)
  • Mapping (类似于Python中字典的概念)

Sequence of Scalars

YAML(ball players)

1
2
3
- Mark McGwire
- Sammy Sosa
- Ken Griffey

Python(YAML)

1
['Mark McGwire', 'Sammy Sosa', 'Ken Griffey']

Mapping Scalars to Scalars

YAML(player statistics)

1
2
3
hr:  65    # Home runs
avg: 0.278 # Batting average
rbi: 147 # Runs Batted In

Pyhton(YAML)

1
{'hr':65, 'avg':0.278, 'rbi':147}

Mapping Scalars to Sequences

YAML(ball clubs in each league)

1
2
3
4
5
6
7
8
american:
- Boston Red Sox
- Detroit Tigers
- New York Yankees
national:
- New York Mets
- Chicago Cubs
- Atlanta Braves

Python(YAML)

1
{'american':['Boston Red Sox', 'Detroit Tigers', 'New York Yankees'], 'national':['New York Mets', 'Chicago Cubs', 'Atlanta Braves']}

Sequence of Mappings

YAML(players’ statistics)

1
2
3
4
5
6
7
8
-
name: Mark McGwire
hr: 65
avg: 0.278
-
name: Sammy Sosa
hr: 63
avg: 0.288

Python(YAML)

1
[{'name':'Mark McGwire', 'hr':65, 'avg':0.278}, {'name':'Sammy Sosa', 'hr':63, 'avg':0.288}]

Sequence of Sequences

YAML

1
2
3
- [name        , hr, avg  ]
- [Mark McGwire, 65, 0.278]
- [Sammy Sosa , 63, 0.288]

Python(YAML)

1
[['name', 'hr', 'avg'], ['Mark McGwire', 65, 0.278], ['Sammy Sosa', 63, 0.288]]

Mapping of Mappings

YAML

1
2
3
4
5
Mark McGwire: {hr: 65, avg: 0.278}
Sammy Sosa: {
hr: 63,
avg: 0.288
}

Python(YAML)

1
{'Mark McGwire':{'hr':65, 'avg':0.278}, 'Sammy Sosa':{'hr':63, 'avg':0.288}}

YAML中的注释

YAML

1
2
3
4
#ball players
- Mark McGwire
- Sammy Sosa
- Ken Griffey

YAML中的文档

在单一一个YAML文件中

  • 使用三个下划线___来分隔文档
  • 使用三个句号...表示结束(一般在通信信道中使用)

YAML(Two Documents in a Stream)

1
2
3
4
5
6
7
8
9
10
# Ranking of 1998 home runs
---
- Mark McGwire
- Sammy Sosa
- Ken Griffey

# Team ranking
---
- Chicago Cubs
- St Louis Cardinals

YAML

1
2
3
4
5
6
7
8
9
10
---
time: 20:03:20
player: Sammy Sosa
action: strike (miss)
...
---
time: 20:03:47
player: Sammy Sosa
action: grand slam
...

实例

YAML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
用YAML来描述一本书《Linux命令行与shell脚本编程大全》

# 《Linux命令行与shell脚本编程大全》描述
--- # begin of document
书名: 'Linux命令行与shell脚本编程大全'
出版社: '人民邮电出版社'
原作者: ['Richard Blum', 'Christine Bresnahan']
译者:
- 武海峰
- 朱巍
前二章节:
- 第一章: 初识Linux Shell
- 第二章: 走进Shell

#end of document

Python(YAML)

1
{'书名':'Linux命令行与shell脚本编程大全', '出版社':'人民邮电出版社', '原作者':['Richard Blum', 'Christine Bresnahan'], '译者':['武海峰', '朱巍'], '前二章节':{'第一章':'初识Linux Shell', '第二章':'走进Shell'}}

参考文档: