在前端开发中,会用到JSON.stringify方法来序列话json数据吧,之前在开发插件的时候读写文件也用到了这个方法,当时的场景是把json写入文件,但是看起来没有换行,所以使用了JSON.stringify,当时用的第三个参数指定缩进的空白字符,还不错,其实还可以过滤数据,一起来看看看吧~~~
首先还是介绍下JSON.stringify,官方的介绍:
JSON.stringify(value[, replacer [, space]])
参数:
value
将要序列化成 一个 JSON 字符串的值。
replacer
如果该参数是一个函数,则在序列化过程中,被序列化的值的每个属性都会经过该函数的转换和处理;如果该参数是一个数组,则只有包含在这个数组中的属性名才会被序列化到最终的 JSON 字符串中;如果该参数为 null 或者未提供,则对象所有的属性都会被序列化。
space
指定缩进用的空白字符串,用于美化输出(pretty-print);如果参数是个数字,它代表有多少的空格;上限为 10。该值若小于 1,则意味着没有空格;如果该参数为字符串(当字符串长度超过 10 个字母,取其前 10 个字母),该字符串将被作为空格;如果该参数没有提供(或者为 null),将没有空格。
常规示范:
console.log(JSON.stringify({ x: 5, y: 6 }));
// expected output: "{"x":5,"y":6}"
console.log(JSON.stringify([new Number(3), new String('false'), new Boolean(false)]));
// expected output: "[3,"false",false]"
console.log(JSON.stringify({ x: [10, undefined, function(){}, Symbol('')] }));
// expected output: "{"x":[10,null,null,null]}"
console.log(JSON.stringify(new Date(2006, 0, 2, 15, 4, 5)));
// expected output: ""2006-01-02T15:04:05.000Z""
原来还可以这样:
看到一片文章的介绍,第二个参数还有过滤的作用
const students = [
{
name: 'akira',
score: 100,
}, {
name: 'John',
score: 60,
}, {
name: 'Jane',
score: 90,
}
];
const textarea = document.getElementById('show-score');
textarea.textContent = JSON.stringify(students, null, 4);
- 第二个参数传['name'],表示只序列化对象中的
"name"
属性,结果只有name属性
const students = [
{
name: 'akira',
score: 100,
}, {
name: 'John',
score: 60,
}, {
name: 'Jane',
score: 90,
}
];
const textarea = document.getElementById('show-score');
textarea.textContent = JSON.stringify(students, ["name"], 4);
- 对象数据也是一样的
const data = {
name: {
name: 'aa',
foo: 'bar',
},
foo: 'bar',
other: {
name: 'bb',
},
}
const result = JSON.stringify(data, ["name"]);
console.log(result); // {name: {name: 'aa'}}
4.如果第二个参数传函数,那么接收key、value 两个参数
const students = [
{
name: 'akira',
score: 100,
}, {
name: 'John',
score: 60,
}, {
name: 'Jane',
score: 90,
}
];
function replacer(key, value) {
if(key === 'score') {
if (value === 100) {
return 'S';
} else if(value >= 90) {
return 'A';
} else if(value >= 70) {
return 'B';
} else if(value >= 50) {
return 'C';
} else {
return 'E';
}
}
return value;
}
const textarea = document.getElementById('show-score');
textarea.textContent = JSON.stringify(students, replacer, 4);
相当于做了替换,看着很熟悉吧,想起了replace方法...
与 JSON.stringify 对应,JSON.parse 也有一个额外的参数,可以传一个函数:
const str = '{"result":true, "count":42}';
const result = JSON.parse(str, (key, value) => {
if(typeof value === 'number') return value * 2;
return value;
});
console.log(result); // {result: true, count: 84}
参考文献,本文示例来自文章的介绍: