yaml

复制代码
---   #文档开始,一个文件中支持多个文档
 doe: "a deer, a female deer"
 ray: "a drop of golden sun"
 pi: 3.14159
 xmas: true
 french-hens: 3
 calling-birds:   #数组,单个破折号开始
   - huey
   - dewey
   - louie
   - fred
 xmas-fifth-day:      #字典
   calling-birds: four
   french-hens: 3
   golden-rings: 5
   partridges:         #嵌套字典
     count: 1
     location: "a pear tree"
   turtle-doves: two
复制代码

在深入研究之前,让我们看看这个文档在 JSON 中的样子。

复制代码
{
  "doe": "a deer, a female deer",
  "ray": "a drop of golden sun",
  "pi": 3.14159,
  "xmas": true,
  "french-hens": 3,
  "calling-birds": [
     "huey",
     "dewey",
     "louie",
     "fred"
  ],
  "xmas-fifth-day": {
  "calling-birds": "four",
  "french-hens": 3,
  "golden-rings": 5,
  "partridges": {
    "count": 1,
    "location": "a pear tree"
  },
  "turtle-doves": "two"
  }
}
复制代码

空格是 YAML 格式的一部分。除非另有说明,否则换行符表示字段的结束。您可以使用缩进来构造 YAML 文档。缩进级别可以是一个或多个空格。规范禁止使用制表符,因为工具对它们的处理方式不同。请考虑此文档。里面的项目缩进两个空格。

foo: bar
pleh: help
stuff:
  foo: bar
  bar: foo

让我们看一下一个简单的 Python 脚本如何查看此文档。我们将其保存为名为foo.yaml的文件。PyYAML 包会将 YAML 文件流映射到字典中。我们将遍历最外层的键和值集,并打印键和每个值的字符串表示形式。您可以在此处找到适合您最喜欢的平台的处理器。

复制代码
Import yaml 

from yaml import load
try:
    from yaml import CLoader as Loader
except ImportError:
    from yaml import Loader

if __name__ == '__main__':

    stream = open("foo.yaml", 'r')
    dictionary = yaml.load(stream)
    for key, value in dictionary.items():
        print (key + " : " + str(value))
复制代码

The output is:

foo : bar
pleh : help
stuff : {'foo': 'bar', 'bar': 'foo'}

 

posted @   wongchaofan  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示