前言

本文档旨在作为一个简短的YAML教程,足以让你开始使用YAML语言。

YAML是一种基于缩进的标记语言,其目标是既易于阅读又易于编写。许多项目使用它是因为它的可读性、简单性以及对许多编程语言的良好支持。

YAML 示例:

  1. execution:
  2. - concurrency: 10
  3. hold-for: 5m
  4. ramp-up: 2m
  5. scenario: yaml_example
  6. scenarios:
  7. yaml_example:
  8. retrieve-resources: false
  9. requests:
  10. - http://example.com/
  11. reporting:
  12. - module: final-stats
  13. - module: console
  14. settings:
  15. check-interval: 5s
  16. default-executor: jmeter
  17. provisioning: local

注意:冒号后面必须有空格。

从示例中可以看到,YAML使用缩进来表示文档结构(与JSON相反,JSON使用括号和大括号)。除此之外,JSON 和 YAML 非常相似。下面是将上面 YAML 转换为 JSON 后的数据:

  1. {
  2. "execution": [
  3. {
  4. "concurrency": 10,
  5. "hold-for": "5m",
  6. "ramp-up": "2m",
  7. "scenario": "json_example"
  8. }
  9. ],
  10. "scenarios": {
  11. "json_example": {
  12. "retrieve-resources": false,
  13. "requests": [
  14. "http://example.com/"
  15. ]
  16. }
  17. },
  18. "reporting": [
  19. {
  20. "module": "final-stats"
  21. },
  22. {
  23. "module": "console"
  24. }
  25. ],
  26. "settings": {
  27. "check-interval": "5s",
  28. "default-executor": "jmeter"
  29. },
  30. "provisioning": "local"
  31. }

普通值:数字、字符串、布尔值

  1. number-value: 42
  2. floating-point-value: 3.141592
  3. boolean-value: true
  4. # strings can be both 'single-quoted` and "double-quoted"
  5. string-value: 'Bonjour'

对应的 JSON 数据:

  1. {
  2. "number-value": 42,
  3. "floating-point-value": 3.141592,
  4. "boolean-value": true,
  5. "string-value": "Bonjour"
  6. }

出于方便的原因,YAML语法还允许不带引号的字符串值:

  1. unquoted-string: Hello World

对应的 JSON 数据:

  1. {
  2. "unquoted-string": "Hello World"
  3. }

集合和字典

集合中的每个元素都必须缩进,并以 - 和空格开头:

  1. jedis:
  2. - Yoda
  3. - Qui-Gon Jinn
  4. - Obi-Wan Kenobi
  5. - Luke Skywalker

对应的 JSON 数据:

  1. {
  2. "jedis": [
  3. "Yoda",
  4. "Qui-Gon Jinn",
  5. "Obi-Wan Kenobi",
  6. "Luke Skywalker"
  7. ]
  8. }

字典是键值映射的集合,所有 key 都区分大小写:

  1. jedi:
  2. name: Obi-Wan Kenobi
  3. home-planet: Stewjon
  4. species: human
  5. master: Qui-Gon Jinn
  6. height: 1.82m

对应的 JSON 数据:

  1. {
  2. "jedi": {
  3. "name": "Obi-Wan Kenobi",
  4. "home-planet": "Stewjon",
  5. "species": "human",
  6. "master": "Qui-Gon Jinn",
  7. "height": "1.82m"
  8. }
  9. }

另外,字典和集合可以互相嵌套,反之亦然:

  1. requests:
  2. # first item of `requests` list is just a string
  3. - http://example.com/
  4. # second item of `requests` list is a dictionary
  5. - url: http://example.com/
  6. method: GET

对应的 JSON 数据:

  1. {
  2. "requests": [
  3. "http:\/\/example.com\/",
  4. {
  5. "url": "http:\/\/example.com\/",
  6. "method": "GET"
  7. }
  8. ]
  9. }

如果需要,还可以对列表和字典使用内联语法:

  1. episodes: [1, 2, 3, 4, 5, 6, 7]
  2. best-jedi: {name: Obi-Wan, side: light}
  1. {
  2. "episodes": [
  3. 1,
  4. 2,
  5. 3,
  6. 4,
  7. 5,
  8. 6,
  9. 7
  10. ],
  11. "best-jedi": {
  12. "name": "Obi-Wan",
  13. "side": "light"
  14. }
  15. }