yaml 进阶语法

  1. 锚点和引用:
    • & 用来建立锚点(defaults)
    • << 表示合并到当前数据
    • *用来引用锚点。
defaluts: &defaults
  sex: man
  age: !!str 18 # 强制转化字符串
  isChinese: true
  isNull: ~

defalut:
  sex: &sex woman # 单个变量引用
  age: 20
  
person_a:
  name: Jack
  <<: *defaults

person_b:
  name: James
  <<: *defaults

person_c:
  name: James
  sex: *sex
  age: 22
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', 'isChinese': True, 'isNull': None}, 'defalut': {'sex': 'woman', 'age': 20}, 'person_a': {'sex': 'man', 'age': '18', 'isChinese': True, 'isNull': None, 'name': 'Jack'}, 'person_b': {'sex': 'man', 'age': '18', 'isChinese': True, 'isNull': None, 'name': 'James'}, 'person_c': {'name': 'James', 'sex': 'woman', 'age': 22}}
  1. 强制转换为字符串及 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'}}
  1. 其他:
    • ~ 表示 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
test1
', 'foo1': 'test test1
', 'foo2': 'test test1', 'bar': ['a', 2, 'c'], 'bar1': {'a': 1, 'b': 2}}
原文地址:https://www.cnblogs.com/ronky/p/14133935.html