YAML学习记录

YAML 是一个可读性高,用来表达资料序列的格式。YAML参考了其他多种语言,包括:C语言、Python、Perl,并从XML、电子邮件的数据格式(RFC 2822)中获得灵感。

1、基本语法规则:
1.大小写敏感
2.使用缩进表示层级关系
3.不允许使用TAB键来缩进,只允许使用空格键来缩进
4.缩进的空格数量不重要
5.使用"#"来表示注释
2、支持的数据格式:
1.对象:键值对的集合,又称映射(mapping) / 哈希(hashes)/ 字典(dictionary)
2.数组: 一组按次序排列的值,又称序列(sequence) / 列表(list)
3.纯量(scalars):单个的,不可再分的值
3、对象

对象的一组键值对,是用冒号结构来表示

animal: cats
students:{zhangsan: boy, xiaohong: girl}
4、数组

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

-cat
-dog
-panda

数据的子结构也是一个数组,可以在该项下面缩进空格来表示层级关系

-
 -cat
 -dog
 -panda

数组也可以采用行内表示法

animal: [cat, dog]

复合结构

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

languages:
  - Ruby
  - Perl
  - Python
websites:
  YAML: yaml.org
  Ruby: ruby-lang.org
  Python: python.org
  Perl: user.perl.org
5、纯量

yaml配置文件,可以解析数字、字符串、布尔类型数据、时间日期格式,也可以对数字、布尔类型数据做强制转换,使其在解析成为字符串类型的数据

# 在yaml中~表示None
~

类型转换

# 在yaml配置中,!!str data表示把数据data强制转换为str类型
age: !!str 18

时间格式

# 时间和日期格式均为iso8601

# 日期表示
data_today:2018-04-22

# 时间格式
# 下面代表北京时间2018,04,22的16:55:30,因为北京位于东八区,所以后面加了08:00,时间的秒可以写到小数点后两位
time_now:2018-04-22T16:55:30+08:00
6、python解析yaml文件

解析环境

pip install pyyaml

解析文件

import yaml
try:
    from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
    from yaml import Loader, Dumper
yaml_file= open("path", "r")
data = yaml.load(yaml_file)
print(data)

使用案例

# 文件名test.yaml
bind1:
  hostname: ubuntu test
  remote_users:
    - user1:
      username: root
      auth_type: ssh-key
      password: 123
    - user2:
      username: gungun
      auth_type: ssh-password
      password: gungun123
  groups:
    - bj_group
  user_profiles:
    - gungun
    - xiangqiangun


python解析test.yaml文件

import yaml

yaml_file = open("test.yaml",'r')
data = yaml.load(yaml_file)
print("data_type:", type(data))
print("data_content:\n", data)

结果:

data_content:
 {'bind1': {'user_profiles': ['gungun', 'xiangqiangun'], 'hostname': 'ubuntu test', 'groups': ['bj_group'], 'remote_users': [{'username': 'root', 'auth_type': 'ssh-key', 'user1': None, 'password': 123}, {'username': 'gungun', 'auth_type': 'ssh-password', 'user2': None, 'password': 'gungun123'}]}}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值