JSON.stringify()
把一个JS对象序列化为一个JSON字符串。
- stringify()函数的基本用法
该函数可以接受三个参数。第一个必填参数为需要序列化的JS对象,第二个可选参数是过滤器,可以是数组或者函数;第三个可选参数是用于缩进结果JSON字符串的选项。
const people = {
name: 'petter',
age: 22,
job: 'doctor',
hobby: ['run', 'music', 'swim']
}
// 1. 传递一个js对象时,直接把js对象转换成json字符串
const peopleText = JSON.stringify(people);
console.log('peopleText: ', peopleText);
//peopleText: {"name":"petter","age":22,"job":"doctor",
// "hobby": ["run","music","swim"]}
// 2. 第二个参数以数组作为过滤器时,过滤出以数组每一项作为key的属性。
const filterArray = JSON.stringify(people, ['name', 'job']);
console.log('filterArray: ', filterArray);
//filterArray: {"name":"petter","job":"doctor"}
// 3. 第二个参数以函数作为过滤器时,函数有两个参数:属性名(key)和属性值(value)。
//可以根据这个key决定对相应的属性执行什么操作。注意:返回undefined会导致属性被忽略。
const filterFun = JSON.stringify(people, (key, value) => {
switch (key) {
case 'name':
return 'herry';
case 'hobby':
return value.join(',');
case 'job':
return undefined;
default:
return value;
}
})
console.log('filterFun: ', filterFun);
//filterFun: {"name":"herry","age":22,"hobby":"run,music,swim"}
// 4. 第三个可选参数可以为数字和字符串。为数字时表示每一级缩进的空格数。
// (每一级最多缩进10个空格,超过10个默认为10)
const indentText = JSON.stringify(people, null, 4);
console.log('indentText: ', indentText);
// indentText: {
// "name": "petter",
// "age": 22,
// "job": "doctor",
// "hobby": [
// "run",
// "music",
// "swim"
// ]
// }
//5. 第三个参数为字符串时,表示用字符串代替空格作为缩进。
// (字符串最多10个字符,超过10个在第10个字符处截断)
const indentText1 = JSON.stringify(people, null, '--');
console.log("indentText1: ", indentText1);
// indentText1: {
// --"name": "petter",
// --"age": 22,
// --"job": "doctor",
// --"hobby": [
// ----"run",
// ----"music",
// ----"swim"
// --]
// }
-
自定义JSON序列化
可以在要序列化的对象中添加toJSON()方法,序列化时会基于这个方法返回适当的JSON表示。
const people = { name: 'petter', age: 22, job: 'doctor', hobby: ['run', 'music', 'swim'], toJSON: function(params) { return this.hobby.join('-'); } } const customJson = JSON.stringify(people); console.log('customJson: ', customJson); //customJson: "run-music-swim" //定义了toJSON()方法简单的返回了hobby属性以‘-’分隔。 //注意:toJSON不能使用箭头函数定义,因为箭头函数的作用域是全局作用域this表示window。
在把JS对象传给JSON.stringify()时会执行如下步骤:
- 如果定义了toJSON方法,会获取该方法的返回值,否则使用默认的序列化。
- 如果提供了第二个参数值,则先过滤。传入给过滤的值就是第一步返回的值。
- 第二步返回的每个值都会相应的进行序列化。
- 如果提供了第三个参数,则进行相应的缩进。
JSON.parse()
把JSON字符串序列化为一个JS对象。
JSON.parse()方法接收两个参数:json字符串和还原函数。还原函数也接收两个参数:属性名(key)和属性值(value)。如果还原函数返回undefined则结果中删除相应的键。
const people = {
name: 'petter',
age: 22,
job: 'doctor',
hobby: ['run', 'music', 'swim']
}
const jsonText = JSON.stringify(people);
console.log("jsonText: ", jsonText);
// jsonText: {"name":"petter","age":22,"job":"doctor",
// "hobby":["run","music","swim"]}
const peopleCopy = JSON.parse(jsonText, (key, value) => {
if (key === 'age') {
return 26;
} else if (key === 'job') {
return undefined; //job属性被删除
} else {
return value;
}
})
console.log("peopleCopy ", peopleCopy);
// peopleCopy { name: 'petter', age: 26, hobby: ['run', 'music', 'swim']}