-
StackOverflow 文件
-
yaml 教程
-
使用錨點和別名來轉換內容
-
使用 YAML 別名來交叉引用 YAML 表中的行
---
person_table:
- &person001
fname: homer
lname: simpson
role: dad
age: 33
- &person002
fname: marge
lname: simpson
role: mom
age: 34
- &person003
fname: peter
lname: griffin
role: dad
age: 34
motto_table:
- &motto001
person: *person001
motto: >
D'oh!! YAML is too complicated!
- &motto002
person: *person002
motto: >
Bart! Listen to your father!
- &motto003
person: *person003
motto: >
Hey! YAML is freakin' sweet!
問題
- 開發人員希望從一個表交叉引用 rows-with-anchors,並在另一個表中使用 rows-as-aliases 連結到它們
解
- 使用 YAML 別名,它交叉引用另一個表中的預定義錨點
- 在 YAML 中,可重用的“transclusion 識別符號”稱為錨點和別名
- 在 YAML 中,可重複使用的“transclusion 識別符號”由字母數字標記組成,前面帶有&符號或星號
合理
- YAML 錨點和別名允許增加資料規範化
- YAML 錨點和別名強制執行
DRY
(不要重複自己)
- 在這個例子中,可以設計和儲存一個與資料庫緊密相符的表結構
- 在此示例中,可以減少資料輸入和檔案大小
陷阱
- 在這個具體的例子中,
yaml.load()
將生成巢狀的詞典
- 這被稱為巢狀字典問題
- 在人名 - 值對下,人的值將是子詞典
- 這可能是不希望的,因為它破壞了桌子結構的均勻性
- 無法正確指定別名將導致資料丟失
- YAML 不支援通過引用進行檔案轉換,因此所有別名和錨點必須存在於同一 yaml 檔案中
- 並非所有 YAML 解析器都可靠地支援錨點和別名
也可以看看
Stackoverflow YAML