本站支持 ActivityPub: [email protected]

YAML

图片来源:https://www.pixiv.net/en/artworks/31241931

YAML是“YAML Ain’t Markup Language”的递归缩写。扩展名可以是.yaml.ymlYAML在线测试

基本语法

  • 大小写敏感
  • 使用缩进表示层级关系
  • 缩进时不允许使用Tab键,只允许使用空格。
  • 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
  • 注释使用#

对象

对象是键值对的集合,“key: value”中冒号右边的空格是必须的

animal: pets
hash: { name: Steve, foo: bar } 

数组

- value” 中,减号右边的空格是必须的

- Cat
- Dog
- Goldfish
-
 - Cat
 - Dog
 - Goldfish
-
 - Apple
 - Pear
 - Orange
- [ Cat, Dog, Goldfish ]
- [ Apple, Pear, Orange ]

混合使用

animal: [ [ Cat, Dog, Goldfish ], [ Apple, Pear, Orange ] ]
companies:
  -
    id: 1
    name: company1
    price: 200W
  -
    id: 2
    name: company2
    price: 500W
languages:
  - Ruby
  - Perl
  - Python 
websites:
  YAML: yaml.org 
  Ruby: ruby-lang.org 
  Python: python.org 
  Perl: use.perl.org

基本类型

boolean: 
    - TRUE   #true,True都可以
    - FALSE  #false,False都可以
float:
    - canonical: 1.23015e+3
    - exponential: 12.3015e+02
    - fixed: 1230.15
    - negative infinity: -.inf
    - not a number: .NaN
int:
    - canonical: 12345
    - decimal: +12345
    - octal: 0o14
    - hexadecimal: 0xC
null:
    nullvalue: ~  #使用~表示null
string:
    - Hello world    #字符串可以不使用引号
    - "Hello world\n" #含有特殊字符用双引号
    - 'Hello world\n'  #单引号会自动转义特殊字符,等价于其他语言中的"Hello world\\n"
    - 'labor''s day'   #使用单引号对单本身引号转义,等价于其他语言中的'labor\'s day'
    - "Sosa did fine.\u263A"  #使用Unicode
date:
    - 2018-02-17    #日期必须使用ISO 8601格式,即yyyy-MM-dd
datetime: 
    - 2018-02-17T15:02:31+08:00    #时间使用ISO 8601格式,时间和日期之间使用T连接,最后使用+代表时区

强制类型转换

e: !!str 123
f: !!str true

多行字符串

多行字符串第二行开始需要空格缩进,最终显示每行内容会使用空格隔开

str: 
  这是一段
  多行
  字符串

等价于

str: '这是一段 多行 字符串'

|保留换行符,>折叠换行

this: |
  one
  two
  three
that: >
  one
  two
  three

等价于

this: "one\ntwo\nthree\n"
thate: "one two three\n"

+表示保留文字块末尾的换行,-表示删除字符串末尾的换行。

s1: |
Foo

s2: |+
Foo


s3: |-
Foo

等价于

s1: "Foo\n"
s2: "Foo\n\n\n"
s3: "Foo"

引用

&用来建立锚点,<<表示合并到当前数据,*用来引用锚点

defaults: &defaults
  adapter:  postgres
  host:     localhost
  
copy_defaults: *defaults

development:
  database: myapp_development
  <<: *defaults

name:
 - &showell Steve 
 - Clark 
 - Brian 
 - Oren 
 - *showell 

等价于

defaults:
  adapter:  postgres
  host:     localhost

copy_defaults: {adapter:  postgres, host: localhost}

development:
  database: myapp_development
  adapter:  postgres
  host:     localhost

name:
 - Steve 
 - Clark 
 - Brian 
 - Oren 
 - Steve 

参考:

知识共享许可协议
本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注