1 概述
YAML(Yet Another Markup Language)表示的内容和JSON类似,但比JSON更加简洁和易读。在使用YAML表示数据的时候,用一个对象的概念来理解更加容易,YAML本质表示的是Key-Value对,Key一般是字符串(也可以有复杂的表示),Value则可以把它们看做对象,如普通对象(字符串、数字等)、数组、嵌套对象等。详细的语法可参考:https://yaml.org/ 。
2 几种对象
2.1 Value是普通对象
普通对象是指只有一个值,而不是那种用Key-Value对表示的字段形式。这些普通对象可以为字符串、数字、布尔值、空值等。
YAML:
name: zhangsan
age: 18
male: true
position: null
其中,字符串可有双引号也可以没有,数字支持科学计数法等(如1.5e+10),空值可以用null、波浪线(~)、或留空等,
对应的JSON格式为:
{
"name": "zhangsan",
"age": 18,
"male": true,
"position": null
}
2.2 Value是数组
数组表示有三种情况:
1、之间在Value用方括号表示
YAML:
colors: [red, blue, yellow]
对应的JSON格式为:
{
"colors": [
"red",
"blue",
"yellow"
]
}
2、数组元素是普通对象,用中杠表示
YAML:
colors:
- red
- blue
- yellow
对应的JSON格式为:
{
"colors": [
"red",
"blue",
"yellow"
]
}
3、数组元素是多字段对象,每个对象的第一个字段key前带中杠,其它字段不需要。也就是一个中杠对应数组中的一个元素。
YAML:
students:
- name: zhangsan
age: 18
male: true
position: null
- name: lisan
age: 19
male: false
position: null
对应的JSON格式为:
{
"students": [
{
"name": "zhangsan",
"age": 18,
"male": true,
"position": null
},
{
"name": "lisan",
"age": 19,
"male": false,
"position": null
}
]
}
2.3 Value是内嵌对象(映射)
内嵌对象主要是相对普通对象而言,是用Key-Value对表示的字段形式,也可以称为哈希、映射、字典等。
YAML:
user:
name: zhangsan
age: 18
male: true
position: null
注意:字段的key前面没有中杠,也只能表示一个对象,字段则可以有多个。
对应的JSON格式为:
{
"user": {
"name": "zhangsan",
"age": 18,
"male": true,
"position": null
}
}
3 小结
理解普通对象、数组、内嵌对象这几种情况的细微区别,就能够在比JSON更简洁的情况下理解和JSON相同的意思。其中数组中的中杠的使用,每个中杠对应一个数组元素。
5242

被折叠的 条评论
为什么被折叠?



