YAML缩进和分隔


YAML缩进和分隔

当您学习任何编程语言时,缩进和分隔是两个主要概念。本章详细讨论了与YAML相关的这两个概念。

YAML的缩进

YAML不包括任何强制性空格。此外,没有必要保持一致。有效的YAML缩进如下所示

a:
   b:
      - c
      -  d
      - e
f:
      "ghi"
  • 在YAML中使用缩进时,您应该记住以下规则:Flow块必须至少包含一些具有周围当前块级别的空格。

  • YAML的流动含量跨越多条线。流内容的开头以 {[

  • 阻止列表项包括与周围块级相同的缩进,因为 - 被视为缩进的一部分。

预期块的示例

请注意以下代码,其中显示了缩进示例

--- !clarkevans.com/^invoice
invoice: 34843
date   : 2001-01-23
bill-to: &id001
   given  : Chris
   family : Dumars
   address:
      lines: |
            458 Walkman Dr.
            Suite #292
      city    : Royal Oak
      state   : MI
      postal  : 48046
ship-to: *id001
product:
    - sku         : BL394D
      quantity    : 4
      description : Basketball
      price       : 450.00
   - sku         : BL4438H
      quantity    : 1
      description : Super Hoop
      price       : 2392.00
tax  : 251.42
total: 4443.52
comments: >
    Late afternoon is best.
    Backup contact is Nancy
    Billsmer @ 338-4338.

分隔字符串

字符串使用双引号字符串分隔。如果转义给定字符串中的换行符,则会将其完全删除并转换为空格值。

实例

在这个例子中,我们将动物列表列为数据类型为string的数组结构。列出的每个新元素都带有连字符前缀,如前缀所述。

-
 - Cat
 - Dog
 - Goldfish
-
 - Python
 - Lion
 - Tiger

另一个解释YAML中字符串表示的例子如下所述。

errors:
    messages:
       already_confirmed: "was already confirmed, please try signing in"
       confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one"
       expired: "has expired, please request a new one"
       not_found: "not found"
       not_locked: "was not locked"
       not_saved:
          one: "1 error prohibited this %{resource} from being saved:"
          other: "%{count} errors prohibited this %{resource} from being saved:"

此示例引用了一组错误消息,用户只需提及关键方面并相应地获取值即可使用。这种YAML模式遵循JSON的结构,YAML的新用户可以理解。