简介
语法规则
- 大小写敏感
- 使用缩进表示层级关系
- 缩进时不允许使用Tab键,只允许使用空格。
- 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
- # 表示注释,从这个字符一直到行尾,都会被解析器忽略
数据结构
- 对象:键值对的集合,又称为映射(mapping)/ 哈希(hashes) / 字典(dictionary
- 数组:一组按次序排列的值,又称为序列(sequence) / 列表(list)
- scalars:单个的、不可再分的值
对象
Mappings use a colon and space (“: ”) to mark each key: value pair
例子:
1
2
3
|
hr: 65 # Home runs
avg: 0.278 # Batting average
rbi: 147 # Runs Batted In
|
数组
Block sequences indicate each entry with a dash and space ( “- ”)
例子:
1
2
3
|
- Mark McGwire
- Sammy Sosa
- Ken Griffey
|
复合结构
例子:
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
|
scalars
类型
YAML 允许使用两个感叹号,强制转换数据类型。例如:e: !!str 123 =》{ e: ‘123’}
- 字符串,默认不使用引号表示,如果字符串之中包含空格或特殊字符,需要放在引号之中。
- 布尔值,布尔值用true和false表示
- 整数
- 浮点数
- Null,null用~表示
- 时间
- 日期
字符串
单引号和双引号
都可以使用,双引号会对特殊字符转义
例如:
1
2
3
4
5
6
7
|
unicode: "Sosa did fine.\u263A"
control: "\b1998\t1999\t2000\n"
hex esc: "\x0d\x0a is \r\n"
single: '"Howdy!" he cried.'
quoted: ' # Not a ''comment''.'
tie-fighter: '|\-*-/|'
|
字符串可以写成多行
从第二行开始,必须有一个单空格缩进。换行符会被转为空格
例如:
等价于
多行字符串
例如:
1
2
3
4
5
6
|
this: |
Foo
Bar
that: >
Foo
Bar
|
等价于
1
|
{ this: 'Foo\nBar\n', that: 'Foo Bar\n' }
|
+
表示保留文字块末尾的换行,-
表示删除字符串末尾的换行。
例如:
1
2
3
4
5
6
7
8
|
s1: |
Foo
s2: |+
Foo
s3: |-
Foo
|
等价于
1
|
{ s1: 'Foo\n', s2: 'Foo\n\n\n', s3: 'Foo' }
|
字符串之中插入 HTML 标记
1
2
3
4
5
|
message: |
<p style="color: red">
段落
</p>
|
等价于
1
|
{ message: '\n<p style="color: red">\n 段落\n</p>\n' }
|
引用
&
用来建立锚点,<<
表示合并到当前数据,*
用来引用锚点。
例子1:
1
2
3
4
5
6
7
8
9
10
11
|
defaults: &defaults
adapter: postgres
host: localhost
development:
database: myapp_development
<<: *defaults
test:
database: myapp_test
<<: *defaults
|
等价于
1
2
3
4
5
6
7
8
9
10
11
12
13
|
defaults:
adapter: postgres
host: localhost
development:
database: myapp_development
adapter: postgres
host: localhost
test:
database: myapp_test
adapter: postgres
host: localhost
|
例子2:
1
2
3
4
5
|
- &showell Steve
- Clark
- Brian
- Oren
- *showell
|
等价于
1
|
[ 'Steve', 'Clark', 'Brian', 'Oren', 'Steve' ]
|