YAML 语言教程与使用案例

image

YAML语言教程与使用案例,如何编与读懂写YAML文件。

YAML概要

YAML 是 “YAML Ain’t a Markup Language”(YAML 不是一种标记语言)的递归缩写。在开发的这种语言时,YAML 的意思其实是:”Yet Another Markup Language”(仍是一种标记语言)。

YAML是一个类似 XML、JSON 的标记性语言。YAML 强调以数据为中心,并不是以标识语言为重点。因而 YAML 本身的定义比较简单,号称“一种人性化的数据格式语言”。

基本语法

1、大小写敏感

2、使用缩进表示层级关系

3、缩进时不允许使用Tab键,只允许使用空格

4、缩进的空格数不重要,只要相同层级的元素左侧对齐即可。【实际使用中建议两个空格作为一个层级的缩进】

5、# 表示注释,从这个字符一直到行尾,都会被解释器忽略

6、冒号,以冒号结尾除外,其他所有冒号后面必须有空格

7、短横线,表示列表项,使用一个短横线加一个空格;多个项使用同样的缩进级别作为同一列表

支持的数据结构

1、对象:键值对的集合,又称为映射(mapping)/ 哈希(hashes) / 字典(dictionary)

2、数组:一组按次序排列的值,又称为序列(sequence) / 列表(list)

3、字面量/纯量(数字、字符串、布尔值)(scalars):单个的、不可再分的值

YAML 组织结构

YAML 文件可以由一或多个文档组成(即相对独立的组织结构组成),文档间使用“---”(三个横线)在每文档开始作为分隔符(可选)。同时,文档也可以使用“...”(三个点号)作为结束符(可选)。如下图所示:

备注:如果只是单个文档,分隔符“---”可省略。

每个文档并不需要使用结束符“...”来表示结束,但是对于网络传输或者流来说,有明确结束的符号,有利于软件处理。(例如不需要知道流关闭就能知道文档结束)

image

Python中yaml模块的使用

Python pip 安装

如果未安装pip,则可以使用以下方法来安装:

1
2
3
# curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py   # 下载安装脚本
# python get-pip.py # 运行安装脚本 或则:python3 get-pip.py 根据使用的Python决定
# pip --version # 版本查看

用哪个版本的 Python 运行安装脚本,pip 就被关联到哪个版本。

pip安装yaml与导入

安装pyyaml

1
# pip install pyyaml  # 或者pip3 install pyyaml

检查是否安装成功:

1、命令行输入:python

2、再输入:import yaml

安装成功后,在脚本里导入的语句,都是 import yaml

YAML-对象数据类型

备注:之所以对yaml文件使用Python进行解析,是因为我们要测验yaml文件格式是否书写正确。

对象数据:是一组键值对,使用冒号结构表示。

单个对象文档文件

yaml文件

1
2
3
4
[root@docker02 yaml]# cat demo_01_obj.yml
---
name: zhang
age: 22

Python解析

1
2
3
4
5
6
7
8
9
10
11
[root@docker02 yaml]# cat demo_01_obj.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: zhang

import yaml

file_path = "./demo_01_obj.yml"
file = open(file_path, 'r')
ys = yaml.load(file.read(), Loader=yaml.Loader)
print ys

输出结果

1
2
[root@docker02 yaml]# python demo_01_obj.py 
{'age': 22, 'name': 'zhang'}

多个对象文档文件

yaml文件,仔细对比下加了”---“和”...“ 的区别

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[root@docker02 yaml]# cat demo_02_obj.yml
---
name: zhang
age: 22
...
---
name: Jane
age: 20
key:
child-key: value
child-key2: value2
...
---
obj: {obj_key1: value1, obj_key2: value2}
...

Python解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[root@docker02 yaml]# cat demo_02_obj.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: zhang

import yaml
import json

file_path = "demo_02_obj.yml"
file = open(file_path, 'r')

ys = yaml.load_all(file.read(), Loader=yaml.Loader)
for y in ys:
# 两种打印方式都尝试下
#print y
print json.dumps(y, indent=2)

输出结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
[root@docker02 yaml]# python demo_02_obj.py
{'age': 22, 'name': 'zhang'}
{'age': 20, 'name': 'Jane', 'key': {'child-key2': 'value2', 'child-key': 'value'}}
{'obj': {'obj_key1': 'value1', 'obj_key2': 'value2'}}
# 或者如下
[root@docker02 yaml]# python demo_02_obj.py
{
"age": 22,
"name": "zhang"
}
{
"age": 20,
"name": "Jane",
"key": {
"child-key2": "value2",
"child-key": "value"
}
}
{
"obj": {
"obj_key1": "value1",
"obj_key2": "value2"
}
}

YAML-数组数据类型

备注:之所以对yaml文件使用Python进行解析,是因为我们要测验yaml文件格式是否书写正确。

数组类型:一组连词线开头的行,构成一个数组

yaml文件

1
2
3
4
5
6
7
8
9
10
[root@docker02 yaml]# cat demo_03_list.yml 
# 书写方式1
color:
- red
- blue
- green
- orange
- white
# 书写方式2:行内表示法
fruits: [orange, apple, banana]

Python解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[root@docker02 yaml]# cat demo_03_list.py 
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: zhang

import yaml
import json

file_path = "demo_03_list.yml"
file = open(file_path, 'r')

ys = yaml.load_all(file.read(), Loader=yaml.Loader)
for y in ys:
# 两种打印方式都尝试下
#print y
print json.dumps(y, indent=2)

输出结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[root@docker02 yaml]# python demo_03_list.py 
{'color': ['red', 'blue', 'green', 'orange', 'white'], 'fruits': ['orange', 'apple', 'banana']}
# 或者结果如下
[root@docker02 yaml]# python demo_03_list.py
{
"color": [
"red",
"blue",
"green",
"orange",
"white"
],
"fruits": [
"orange",
"apple",
"banana"
]
}

YAML-复合结构

备注:之所以对yaml文件使用Python进行解析,是因为我们要测验yaml文件格式是否书写正确。

复合结构:对象和数组可以结合使用,形成复合结构

yaml文件,注意其书序格式,并细细对比输出结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[root@docker02 yaml]# cat demo_04_compose.yml
shop: GoodShopping
address: BJ
goods:
Food:
- sell_time: "AM 08:30"
food01: rice
food02: pork
Fruits:
- sell_time: "AM 09:00"
- fruit01: orange
price: 3.50
- fruit02: banana
price: 3.00
clothes:
- sell_time: "AM 09:30"
- clothe01
- clothe02

Python解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[root@docker02 yaml]# cat demo_04_compose.py 
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: zhang

import yaml
import json

file_path = "demo_04_compose.yml"
file = open(file_path, 'r')

ys = yaml.load_all(file.read(), Loader=yaml.Loader)
for y in ys:
# 两种打印方式都尝试下
print y
#print json.dumps(y, indent=2)

输出结果,仔细对比下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
[root@docker02 yaml]# python demo_04_compose.py 
{'shop': 'GoodShopping', 'goods': {'Food': [{'food02': 'pork', 'sell_time': 'AM 08:30', 'food01': 'rice'}], 'Fruits': [{'sell_time': 'AM 09:00'}, {'fruit01': 'orange', 'price': 3.5}, {'price': 3.0, 'fruit02': 'banana'}], 'clothes': [{'sell_time': 'AM 09:30'}, 'clothe01', 'clothe02']}, 'address': 'BJ'}
# 或者结果如下
[root@docker02 yaml]# python demo_04_compose.py
{
"shop": "GoodShopping",
"goods": {
"Food": [
{
"food02": "pork",
"sell_time": "AM 08:30",
"food01": "rice"
}
],
"Fruits": [
{
"sell_time": "AM 09:00"
},
{
"fruit01": "orange",
"price": 3.5
},
{
"price": 3.0,
"fruit02": "banana"
}
],
"clothes": [
{
"sell_time": "AM 09:30"
},
"clothe01",
"clothe02"
]
},
"address": "BJ"
}

YAML-纯量数据类型

备注:之所以对yaml文件使用Python进行解析,是因为我们要测验yaml文件格式是否书写正确。

纯量是最基本的,不可再分的值,包括:

1
2
3
4
5
6
7
字符串
布尔值
整数
浮点数
Null
时间
日期

常用数据类型的表示格式进行了约定

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
[root@docker02 yaml]# cat demo_05_scalars.yml
boolean:
- TRUE # true,True都可以
- FALSE # false,False都可以
float:
- 3.14
- 6.8523015e+5 #可以使用科学计数法
int:
- 123
null:
nodeName: 'node'
parent: ~ # 使用~表示null
string:
- 哈哈
- 'Hello world' # 可以使用双引号或者单引号包裹特殊字符
- newline
newline2 # 字符串可以拆成多行,非尾行的每一行换行符都转为空格
date:
- 2018-02-17 # 日期必须使用ISO 8601格式,即yyyy-MM-dd
datetime:
- 2018-02-17T15:02:31+08:00 #时间使用ISO 8601格式,时间和日期之间使用T连接,最后使用+代表时区

双叹号强制转换类型

yaml文件

1
2
3
4
5
6
7
[root@docker02 yaml]# cat demo_06_switch.yml 
# 原信息
ori01: 3.14
ori02: "123"
# 强制转换
int_str: !!str 3.14 # value 整数强制转换为字符串
str_int: !!int "123" # value 字符串强制转换为整数

Python解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[root@docker02 yaml]# cat demo_06_switch.py 
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: zhang

import yaml
import json

file_path = "demo_06_switch.yml"
file = open(file_path, 'r')

ys = yaml.load_all(file.read(), Loader=yaml.Loader)
for y in ys:
# 两种打印方式都尝试下
print y
#print json.dumps(y, indent=2)

输出结果,仔细对比下

1
2
3
4
5
6
7
8
9
10
[root@docker02 yaml]# python demo_06_switch.py 
{'ori01': 3.14, 'int_str': '3.14', 'ori02': '123', 'str_int': 123}
# 或者输出如下
[root@docker02 yaml]# python demo_06_switch.py
{
"ori01": 3.14,
"int_str": "3.14",
"ori02": "123",
"str_int": 123
}

YAML-引用

备注:之所以对yaml文件使用Python进行解析,是因为我们要测验yaml文件格式是否书写正确。

& 用来建立锚点(defaults),<< 表示合并到当前数据,* 用来引用锚点。

yaml文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[root@docker02 yaml]# cat demo_07_anchor.yml
---
hr:
- Mark McGwire
# Following node labeled SS
- &SS Sammy Sosa # 定义要复制的数据
rbi:
- *SS # Subsequent occurrence 这里是数据复制目标
- Ken Griffey
...
---
defaults: &defaults
adapter: postgres
host: localhost

development:
database: myapp_development
<<: *defaults

test:
database: myapp_test
info: *defaults
...

Python解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[root@docker02 yaml]# cat demo_07_anchor.py 
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: zhang

import yaml
import json

file_path = "demo_07_anchor.yml"
file = open(file_path, 'r')

ys = yaml.load_all(file.read(), Loader=yaml.Loader)
for y in ys:
# 两种打印方式都尝试下
print y
#print json.dumps(y, indent=2)

输出结果,仔细对比下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
[root@docker02 yaml]# python demo_07_anchor.py 
{'hr': ['Mark McGwire', 'Sammy Sosa'], 'rbi': ['Sammy Sosa', 'Ken Griffey']}
{'development': {'adapter': 'postgres', 'host': 'localhost', 'database': 'myapp_development'}, 'test': {'info': {'adapter': 'postgres', 'host': 'localhost'}, 'database': 'myapp_test'}, 'defaults': {'adapter': 'postgres', 'host': 'localhost'}}
# 或者结果如下
[root@docker02 yaml]# python demo_07_anchor.py
{
"hr": [
"Mark McGwire",
"Sammy Sosa"
],
"rbi": [
"Sammy Sosa",
"Ken Griffey"
]
}
{
"development": {
"adapter": "postgres",
"host": "localhost",
"database": "myapp_development"
},
"test": {
"info": {
"adapter": "postgres",
"host": "localhost"
},
"database": "myapp_test"
},
"defaults": {
"adapter": "postgres",
"host": "localhost"
}
}

YAML-字符串

备注:之所以对yaml文件使用Python进行解析,是因为我们要测验yaml文件格式是否书写正确。

字符串是最常见,也是最复杂的一种数据类型。

字符串默认不使用引号表示。

1
str: 这是一行字符串

如果字符串之中包含空格或特殊字符,需要放在引号之中。

1
str: '内容: 字符串'

单引号和双引号都可以使用,双引号不会对特殊字符转义。

1
2
s1: '内容\n字符串'
s2: "内容\n字符串"

单引号之中如果还有单引号,必须连续使用两个单引号转义。

1
str: 'labor''s day'

字符串可以写成多行,从第二行开始,必须有空格缩进。换行符会被转为空格

1
2
3
str: 这是一段
多行
字符串

多行字符串可以使用 | 保留换行符,也可以使用 > 折叠换行。

1
2
3
4
5
6
this: |
Foo
Bar
that: >
Foo
Bar

+ 表示保留字符串行末尾的换行,- 表示删除字符串末尾的换行。

1
2
3
4
5
6
7
8
s1: |
Foo

s2: |+
Foo

s3: |-
Foo

字符串之中可以插入 HTML 标记。

1
2
3
4
5
message: |

<p style="color: red">
段落
</p>

字符串测验案例

yaml文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
[root@docker02 yaml]# cat demo_08_str.yml 
str01: zhangsan
str02: 'Q: What are you doing?'

str03: 'zhangsan\nlisi\nwangwu'
str04: "zhangsan\nlisi\nwangwu"

str05: 'What''s your name?'
str06: "What's your name?"

str07:
'Ken: Hello,
My name is Ken.
What''s your name?'

str08:
"Ken: Hello,
My name is Ken.
What's your name?"

str11: |
111
222
333
str12: >
aaa xxx
bbb yyy
ccc zzz

# 之后有2行空行
str16: |
zhangsan
lisi
wangwu


# 之后有2行空行
str17: |+
zhangsan
lisi
wangwu


# 之后有2行空行
str18: |-
zhangsan
lisi
wangwu


message: |

<p style="color: red">
one line str
</p>

Python解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[root@docker02 yaml]# cat demo_08_str.py 
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: zhang

import yaml
import json

file_path = "demo_08_str.yml"
file = open(file_path, 'r')

ys = yaml.load_all(file.read(), Loader=yaml.Loader)
for y in ys:
# 两种打印方式都尝试下
print y
#print json.dumps(y, indent=2)

输出结果,仔细对比下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[root@docker02 yaml]# python demo_08_str.py 
{'str02': 'Q: What are you doing?', 'str01': 'zhangsan', 'str05': "What's your name?", 'str08': "Ken: Hello, My name is Ken. What's your name?", 'str06': "What's your name?", 'str18': 'zhangsan\nlisi\nwangwu', 'str17': 'zhangsan\nlisi\nwangwu\n\n\n', 'str16': 'zhangsan\nlisi\nwangwu\n', 'message': u'\n<p style="color: red">\n one line str\n</p>\n', 'str03': 'zhangsan\\nlisi\\nwangwu', 'str04': 'zhangsan\nlisi\nwangwu', 'str12': 'aaa xxx bbb yyy ccc zzz\n', 'str11': '111\n222\n333\n', 'str07': "Ken: Hello, My name is Ken. What's your name?"}
# 或者输出如下
[root@docker02 yaml]# python demo_08_str.py
{
"str02": "Q: What are you doing?",
"str01": "zhangsan",
"str05": "What's your name?",
"str08": "Ken: Hello, My name is Ken. What's your name?",
"str06": "What's your name?",
"str18": "zhangsan\nlisi\nwangwu",
"str17": "zhangsan\nlisi\nwangwu\n\n\n",
"str16": "zhangsan\nlisi\nwangwu\n",
"message": "\n<p style=\"color: red\">\n one line str\n</p>\n",
"str03": "zhangsan\\nlisi\\nwangwu",
"str04": "zhangsan\nlisi\nwangwu",
"str12": "aaa xxx bbb yyy ccc zzz\n",
"str11": "111\n222\n333\n",
"str07": "Ken: Hello, My name is Ken. What's your name?"
}

完毕!


<-------------the end------------->
lightzhang wechat
欢迎扫一扫,订阅我的微信公众号!
坚持原创分享,你的支持就是我最大的动力!