YAML 是 “YAML Ain’t a Markup Language”(YAML 不是一种标记语言)的递归缩写。在开发的这种语言时,YAML 的意思其实是:”Yet Another Markup Language”(仍是一种标记语言)。
YAML 的语法和其他高级语言类似,并且可以简单表达清单、散列表,标量等数据形态。它使用空白符号缩进和大量依赖外观的特色,特别适合用来表达或编辑数据结构、各种配置文件、倾印调试内容、文件大纲(例如:许多电子邮件标题格式和YAML非常接近)。
YAML 的配置文件后缀为 .yml
基本语法
- 大小写敏感
- 使用缩进表示层级关系
- 缩进时不允许使用Tab键,只允许使用空格。
- 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
数据类型
- 对象:键值对的集合,又称为映射(mapping)/ 哈希(hashes) / 字典(dictionary)
- 数组:一组按次序排列的值,又称为序列(sequence) / 列表(list)
- 纯量(scalars):单个的、不可再分的值
对象
1 2 3
| info: version: "1.0.0" title: "CMAP website api"
|
转换为js
1
| info: { version: '1.0.0', title: 'CMAP website api' }
|
第二种写法
1
| info: {version: 1.0.0, title: CMAP website api}
|
转换为js
1
| info: { version: '1.0.0', title: 'CMAP website api' }
|
数组
使用 -
1 2 3 4
| - name: "Website" - name: "Site" - name: "Components" - name: "Variation"
|
转换成js
1 2 3 4 5 6
| [ { name: 'Website' }, { name: 'Site' }, { name: 'Components' }, { name: 'Variation' } ]
|
1 2 3 4 5
| - - name: "Website" - name: "Site" - name: "Components" - name: "Variation"
|
转换成js
1 2 3 4 5 6
| [[ { name: 'Website' }, { name: 'Site' }, { name: 'Components' }, { name: 'Variation' } ]]
|
1 2 3 4 5
| tags: - name: "Website" - name: "Site" - name: "Components" - name: "Variation"
|
转换成js
1 2 3 4 5 6
| tags: [ { name: 'Website' }, { name: 'Site' }, { name: 'Components' }, { name: 'Variation' } ]
|
复合结构
1 2 3 4 5 6 7 8 9 10 11 12 13
| swagger: "2.0" info: version: "1.0.0" title: "CMAP website api" basePath: "/api" host: "local.cmap.com" tags: - name: "Website" - name: "Site" - name: "Components" - name: "Variation" schemes: - http
|
转换成js
1 2 3 4 5 6 7 8 9 10 11 12 13
| { swagger: '2.0', info: { version: '1.0.0', title: 'CMAP website api' }, basePath: '/api', host: 'local.cmap.com', tags: [ { name: 'Website' }, { name: 'Site' }, { name: 'Components' }, { name: 'Variation' } ], schemes: [ 'http' ] }
|
转换code
_config.yml
1 2 3 4 5 6 7 8 9 10 11 12 13
| swagger: "2.0" info: version: "1.0.0" title: "CMAP website api" basePath: "/api" host: "local.cmap.com" tags: - name: "Website" - name: "Site" - name: "Components" - name: "Variation" schemes: - http
|
transform.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| const yaml = require('js-yaml'); const fs = require('fs'); const path = require('path')
const ymlFile = fs.readFileSync(path.resolve(__dirname, '_config.yml'), { encoding: 'utf-8' })
const ymldata = yaml.load(ymlFile);
console.log(ymldata);
|
https://www.ruanyifeng.com/blog/2016/07/yaml.html