YAML - 縮排和分隔



縮排和分隔是學習任何程式語言時兩個主要的理念。本章詳細討論了與 YAML 相關的這兩個概念。

YAML 的縮排

YAML 不包含任何強制空格。此外,無需保持一致。有效的 YAML 縮排如下所示:

a:
   b:
      - c
      -  d
      - e
f:
      "ghi"
  • 在使用 YAML 中的縮排時,您應該記住以下規則:流塊必須至少使用一些空格縮排,與周圍的當前塊級別相同。

  • 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.

字串的分隔

字串使用雙引號字串分隔。如果在給定字串中轉義換行符,則會將其完全刪除並轉換為空格值。

示例

在此示例中,我們重點列出了作為陣列結構列出的動物,資料型別為字串。每個新元素都以連字元作為字首列出,如字首所示。

-
 - 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 新手來說很容易理解。

廣告

© . All rights reserved.