YAML的数据结构
YAML的设计者认为在配置文件中所要表达的数据内容有三种类型
- Scalars(标量,如字符串和数字等)
- Sequence (序列,类似于Python中列表的概念)
- Mapping (类似于Python中字典的概念)
Sequence of Scalars
YAML(ball players)
- Mark McGwire
- Sammy Sosa
- Ken Griffey
Python(YAML)
['Mark McGwire', 'Sammy Sosa', 'Ken Griffey']
Mapping Scalars to Scalars
YAML(player statistics)
hr: 65 # Home runs
avg: 0.278 # Batting average
rbi: 147 # Runs Batted In
Pyhton(YAML)
{'hr':65, 'avg':0.278, 'rbi':147}
Mapping Scalars to Sequences
YAML(ball clubs in each league)
american:
- Boston Red Sox
- Detroit Tigers
- New York Yankees
national:
- New York Mets
- Chicago Cubs
- Atlanta Braves
Python(YAML)
{'american':['Boston Red Sox', 'Detroit Tigers', 'New York Yankees'], 'national':['New York Mets', 'Chicago Cubs', 'Atlanta Braves']}
Sequence of Mappings
YAML(players’ statistics)
-
name: Mark McGwire
hr: 65
avg: 0.278
-
name: Sammy Sosa
hr: 63
avg: 0.288
Python(YAML)
[{'name':'Mark McGwire', 'hr':65, 'avg':0.278}, {'name':'Sammy Sosa', 'hr':63, 'avg':0.288}]
Sequence of Sequences
YAML
- [name , hr, avg ]
- [Mark McGwire, 65, 0.278]
- [Sammy Sosa , 63, 0.288]
Python(YAML)
[['name', 'hr', 'avg'], ['Mark McGwire', 65, 0.278], ['Sammy Sosa', 63, 0.288]]
Mapping of Mappings
YAML
Mark McGwire: {hr: 65, avg: 0.278}
Sammy Sosa: {
hr: 63,
avg: 0.288
}
Python(YAML)
{'Mark McGwire':{'hr':65, 'avg':0.278}, 'Sammy Sosa':{'hr':63, 'avg':0.288}}
YAML中的注释
YAML
#ball players
- Mark McGwire
- Sammy Sosa
- Ken Griffey
YAML中的文档
在单一一个YAML文件中
- 使用三个下划线
___
来分隔文档 - 使用三个句号
...
表示结束(一般在通信信道中使用)
YAML(Two Documents in a Stream)
# Ranking of 1998 home runs
---
- Mark McGwire
- Sammy Sosa
- Ken Griffey
# Team ranking
---
- Chicago Cubs
- St Louis Cardinals
YAML
---
time: 20:03:20
player: Sammy Sosa
action: strike (miss)
...
---
time: 20:03:47
player: Sammy Sosa
action: grand slam
...
实例
YAML
用YAML来描述一本书《Linux命令行与shell脚本编程大全》
# 《Linux命令行与shell脚本编程大全》描述
--- # begin of document
书名: 'Linux命令行与shell脚本编程大全'
出版社: '人民邮电出版社'
原作者: ['Richard Blum', 'Christine Bresnahan']
译者:
- 武海峰
- 朱巍
前二章节:
- 第一章: 初识Linux Shell
- 第二章: 走进Shell
#end of document
Python(YAML)
{'书名':'Linux命令行与shell脚本编程大全', '出版社':'人民邮电出版社', '原作者':['Richard Blum', 'Christine Bresnahan'], '译者':['武海峰', '朱巍'], '前二章节':{'第一章':'初识Linux Shell', '第二章':'走进Shell'}}
参考文档: