在JavaScript中,可以Json.stringfy()的方法将值转换为字符串(string)
一般的用法如下:
const value = {
name: 'zhansan',
age:18,
}
const jsonValue = JSON.stringify(value);
获得的jsonValue结果是
{"name":"zhansan","age":18}
除了以上的用法,还有其他的拓展用法的:
在源码中,我们可以看出
interface JSON {
/**
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
* @param value A JavaScript value, usually an object or array, to be converted.
* @param replacer A function that transforms the results.
* @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
*/
stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string;
/**
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
* @param value A JavaScript value, usually an object or array, to be converted.
* @param replacer An array of strings and numbers that acts as an approved list for selecting the object properties that will be stringified.
* @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
*/
stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string;
}
从原码中可以发现还是存在两位两个参数: replacer 和 space
1. replacer
这一个参数最主要用于控制结果的输出,即是,有时候我们并不希望我们的全部值被输出,可能我们会通过去处理值,再输出,但是这样实际上是浪费了存储空间的,而 JSON.stringify() 这个方法就提供了replacer这个选项。
从上述代码中可以看出,其有两种形式,一种是函数形式,一种是数组形式
1. 使用数组的形式,只转换数组中存在的值
const value = {
name: 'zhansan',
age:18,
sex:'box',
hobby: 'running',
}
const jsonValue = JSON.stringify(value, ['name','age']);
console.log(jsonValue)
// {"name":"zhansan","age":18}
2. 通过函数形式去处理
const value = {
name: 'zhansan',
age:18,
sex:'box',
hobby: 'running',
}
const jsonValue = JSON.stringify(value, ((key, val) => {
if(key === 'age'){
return undefined
}
return val;
}));
console.log(jsonValue)
//{"name":"zhansan","sex":"box","hobby":"running"}
2. space
参数用来控制结果字符串里面的间距。如果是一个数字,则在字符串化时每一级别会比上一级别缩进多这个数字值的空格(最多 10 个空格);如果是一个字符串,则每一级别会比上一级别多缩进该字符串(或该字符串的前 10 个字符)。
const value = {
name: 'zhansan',
age:18,
sex:'box',
hobby: 'running',
}
const jsonValue = JSON.stringify(value, null, 1);
console.log(jsonValue)
输出结果
{
"name": "zhansan",
"age": 18,
"sex": "box",
"hobby": "running"
}
还有一个 toJson的方法,就是在对象中添加 toJson 这一个方法,当进行序列化时,被序列化不是该对象,而是此方法,
const value = {
name: 'zhansan',
age:18,
sex:'box',
hobby: 'running',
toJSON: function () {
return 'this is a test ';
}
}
const jsonValue = JSON.stringify(value, null, 5);
console.log(jsonValue)
得到的结果
"this is a test "