YAML介绍
yaml是什么
YAML是专门用来写配置文件的语言,远比JSON格式方便。
YAML语言的设计目标,就是方便人类读写。
YAML是一种比XML和JSON更轻的文件格式,也更简单更强大,它可以通过缩进来表示结构。
YAML 的配置文件后缀为 .yml。
yaml语法规则
- 大小写敏感
- 使用缩进表示层级关系
- 缩进时不允许使用Tab键,只允许使用空格。
- 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
- #表示注释,从这个字符一直到行尾,都会被解析器忽略,这个和python的注释一样
- 列表里的项用-来代表,字典里的键值对用:分隔
yaml数据结构
YAML 支持以下几种数据类型:
- 对象:键值对的集合,又称为映射(mapping)/ 哈希(hashes) / 字典(dictionary)
- 数组:一组按次序排列的值,又称为序列(sequence) / 列表(list)
- 纯量(scalars):单个的、不可再分的值
YAML 对象
对象键值对使用冒号结构表示 key: value,冒号后面要加一个空格。
也可以使用 **key:{key1: value1, key2: value2, …}**。
还可以使用缩进表示层级关系;
| 12
 3
 
 | key: child-key: value
 child-key2: value2
 
 | 
较为复杂的对象格式,可以使用问号加一个空格代表一个复杂的 key,配合一个冒号加一个空格代表一个 value:
| 12
 3
 4
 5
 6
 
 | ?  - complexkey1
 - complexkey2
 :
 - complexvalue1
 - complexvalue2
 
 | 
意思即对象的属性是一个数组 [complexkey1,complexkey2],对应的值也是一个数组 [complexvalue1,complexvalue2]
YAML 数组
以 - 开头的行表示构成一个数组:
YAML 支持多维数组,可以使用行内表示:
| 1
 | key: [value1, value2, ...]
 | 
数据结构的子成员是一个数组,则可以在该项下面缩进一个空格。
一个相对复杂的例子:
| 12
 3
 4
 5
 6
 7
 8
 9
 
 | companies:-
 id: 1
 name: company1
 price: 200W
 -
 id: 2
 name: company2
 price: 500W
 
 | 
意思是 companies 属性是一个数组,每一个数组元素又是由 id、name、price 三个属性构成。
数组也可以使用流式(flow)的方式表示:
| 1
 | companies: [{id: 1,name: company1,price: 200W},{id: 2,name: company2,price: 500W}]
 | 
复合结构
数组和对象可以构成复合结构,例:
| 12
 3
 4
 5
 6
 7
 8
 9
 
 | languages:- Ruby
 - Perl
 - Python
 websites:
 YAML: yaml.org
 Ruby: ruby-lang.org
 Python: python.org
 Perl: use.perl.org
 
 | 
转换为 json 为:
| 12
 3
 4
 5
 6
 7
 8
 9
 
 | { languages: [ 'Ruby', 'Perl', 'Python'],
 websites: {
 YAML: 'yaml.org',
 Ruby: 'ruby-lang.org',
 Python: 'python.org',
 Perl: 'use.perl.org'
 }
 }
 
 | 
纯量
纯量是最基本的,不可再分的值,包括:
- 字符串
- 布尔值
- 整数
- 浮点数
- Null
- 时间
- 日期
使用一个例子来快速了解纯量的基本使用:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 
 | boolean: - TRUE
 - FALSE
 float:
 - 3.14
 - 6.8523015e+5
 int:
 - 123
 - 0b1010_0111_0100_1010_1110
 null:
 nodeName: 'node'
 parent: ~
 string:
 - 哈哈
 - 'Hello world'
 - newline
 newline2
 date:
 - 2018-02-17
 datetime:
 -  2018-02-17T15:02:31+08:00
 
 | 
引用
& 锚点和 ***** 别名,可以用来引用:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 
 | defaults: &defaultsadapter:  postgres
 host:     localhost
 
 development:
 database: myapp_development
 <<: *defaults
 
 test:
 database: myapp_test
 <<: *defaults
 
 | 
相当于:
| 12
 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
 
 | 
& 用来建立锚点(defaults),**<<** 表示合并到当前数据,***** 用来引用锚点。
分段
在同一个yaml文件中,可以用---来分段,这样可以将多个文档写在一个文件中。如:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 
 | ---development:
 database: myapp_development
 adapter:  postgres
 host:     localhost
 
 ---
 test:
 database: myapp_test
 adapter:  postgres
 host:     localhost
 
 | 
通过python读取出来的数据格式为:
| 12
 
 | {'development': {'database':'myapp_development', 'adapter':'postgres', 'host':'localhost'}}{'test': {'database':'test', 'adapter':'postgres', 'host':'localhost'}}
 
 | 
二、PyYaml的简单使用
PyYaml是Python的一个专门针对YAML文件操作的模块,使用起来非常简单
使用起来非常简单,就像json、pickle一样,load、dump就足够我们使用了。
load()
返回一个对象
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 
 | import yaml
 yaml_str = """
 name: 一条大河
 age: 1956
 job: Singer
 """
 
 y = yaml.load(yaml_str, Loader=yaml.SafeLoader)
 print(y)
 
 | 
运行结果:
| 1
 | {'name': '一条大河', 'age': 1956, 'job': 'Singer'}
 | 
load_all()
生成一个迭代器
如果string或文件包含几块yaml文档,可以使用yaml.load_all来解析全部的文档。
yaml_test.yaml文件内容:
| 12
 3
 4
 5
 6
 
 | ---name: qiyu
 age: 20岁
 ---
 name: qingqing
 age: 19岁
 
 | 
操作yaml文件的test.py文件如下:
| 12
 3
 4
 5
 6
 
 | import yaml
 with open("./yaml_test", 'r', encoding='utf-8') as ymlfile:
 cfg = yaml.load_all(ymlfile, Loader=yaml.SafeLoader)
 for data in cfg:
 print(data)
 
 | 
运行结果:
| 12
 
 | {'name': 'qiyu', 'age': '20岁'}{'name': 'qingqing', 'age': '19岁'}
 
 | 
dump()
将一个python对象生成为yaml文档
| 12
 3
 4
 5
 6
 7
 8
 
 | import yaml
 json_data = {'name': '一条大河',
 'age': 1956,
 'job': ['Singer','Dancer']}
 
 y = yaml.dump(json_data, default_flow_style=False).encode('utf-8').decode('unicode_escape')
 print(y)
 
 | 
运行结果:
| 12
 3
 4
 5
 
 | age: 1956job:
 - Singer
 - Dancer
 name: "一条大河"
 
 | 
使用dump()传入参数,可以直接把内容写入到yaml文件:
| 12
 3
 4
 5
 6
 7
 8
 
 | import yaml
 json_data = {'name': '一条大河',
 'age': 1956,
 'job': ['Singer', 'Dancer']}
 with open('./yaml_write.yaml', 'w') as f:
 y = yaml.dump(json_data, f)
 print(y)
 
 | 
写入内容后的yaml_write.yaml:

yaml.dump_all()
将多个段输出到一个文件中
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 
 | import yaml
 obj1 = {"name": "river", "age": 2019}
 obj2 = ["Lily", 1956]
 obj3 = {"gang": "ben", "age": 1963}
 obj4 = ["Zhuqiyu", 1994]
 
 with open('./yaml_write_all.yaml', 'w', encoding='utf-8') as f:
 y = yaml.dump([obj1, obj2, obj3, obj4], f)
 print(y)
 
 with open('./yaml_write_all.yaml', 'r') as r:
 y1 = yaml.load(r, Loader=yaml.SafeLoader)
 print(y1)
 
 | 
写入内容后的yaml_write_all.yaml:
