锚点与别名 使用 &
定义锚点,使用*
应用别名
1 2 3 4 5 6 7 8 9 10 11 12 defaults: &defaults timeout: 30 retries: 5 service1: <<: *defaults url: http://example.com/servicel service2: <<: *defaults url: http://example.com/service2 retries: 10
结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 defaults: timeout: 30 retries: 5 service1: timeout: 30 retries: 5 url: http://example.com/service1 service2: timeout: 30 retries: 10 url: http://example.com/service2
合并键 使用<<
操作符来合并多个映射
1 2 3 4 5 6 base: &base name: example extended: <<: *base description: This is an extended example
结果:
1 2 3 4 5 6 base: name: example extended: name: example description: This is an extended example.
复杂数据结构 **yaml ** 支持嵌套和组合不同的数据类型
1 2 3 4 5 6 7 8 9 10 servers: - name: web ip: 10.0 .0 .1 roles: - webserver - database - name: app ip: 10.0 .0 .2 roles: - application
结果:
1 2 3 4 5 6 7 8 9 10 servers: - name: web ip: 10.0 .0 .1 roles: - webserver - database - name: app ip: 10.0 .0 .2 roles: - application
自定义标签 可以通过添加特定前缀来定义自定义标签
1 2 3 custom_object: !mytag name: custom_name value: 42
结果:
1 2 3 4 custom_object: !!mytag name: custom_name value: 42
多行字符串 使用 |
进行保留换行,使用 >
将换行为空格
1 2 3 4 5 6 7 description: | This is a multiline string. It retains line breaks. short_description: > This is a short description that will be folded into a single line.
字典中的复杂键 yaml 允许使用复杂的类型作为映射的键
1 2 3 4 5 6 ? - &ref1 value1 ? - &ref2 value2 ? - &ref3 value3 : <<: *ref1 description: "This entry uses a complex key"
结果:
1 2 3 4 - value1 - value2 - value3: description: "This entry uses a complex key"
使用JSON格式 yaml 可以轻松转化为 JSON ,支持使用JSON 的语法来表示数据
1 2 3 4 { "name": "example" , "values": [1 , 2 , 3 ] }