yaml 進階語法
阿新 • • 發佈:2020-12-14
- 錨點和引用:
- & 用來建立錨點(defaults)
- << 表示合併到當前資料
- *用來引用錨點。
defaluts: &defaults
sex: man
age: 18
person_a:
name: Jack
<<: *defaults
person_b:
name: James
<<: *defaults
import yaml def test_quote(): with open('quote.yml', encoding='utf-8') as f: datas = yaml.safe_load(f) print(datas) OutPut[1]: {'defaluts': {'sex': 'man', 'age': 18}, 'person_a': {'sex': 'man', 'age': 18, 'name': 'Jack'}, 'person_b': {'sex': 'man', 'age': 18, 'name': 'James'}}
- 強制轉換為字串及 Boolean 值
defaluts: &defaults sex: man age: !!str 18 # 強制轉化字串 isChinese: true # Boolean 值 person_a: name: Jack <<: *defaults person_b: name: James <<: *defaults OutPut[2]:{'defaluts': {'sex': 'man', 'age': '18', 'isChinese': True}, 'person_a': {'sex': 'man', 'age': '18', 'isChinese': True, 'name': 'Jack'}, 'person_b': {'sex': 'man', 'age': '18', 'isChinese': True, 'name': 'James'}}
- 其他:
- ~ 表示 null
- 多行字串可以使用|保留換行符,也可以使用>摺疊換行。
- 所有鍵值對寫成一個行內物件。
-
表示註釋
test: isNull: ~ # ~ 表示 null foo: | test test1 foo1: > test test1 foo2: test test1 bar: ['a', 2, 'c'] bar1: {"a":1,"b":2} OutPut[3]:{'test': {'isNull': None}, 'foo': 'test\ntest1\n', 'foo1': 'test test1\n', 'foo2': 'test test1', 'bar': ['a', 2, 'c'], 'bar1': {'a': 1, 'b': 2}}