JSON.stringify 详细使用
官方定义
interface JSON {
/**
* Converts a JavaScript Object Notation (JSON) string into an object.
* @param text A valid JSON string.
* @param reviver A function that transforms the results. This function is called for each member of the object.
* If a member contains nested objects, the nested objects are transformed before the parent object is.
*/
parse(text: string, reviver?: (this: any, key: string, value: any) => any): any;
/**
* 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 a 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;
}
stringify 那些类型可显示
class stringifyVisualble {
a = '123';
b = () => {};
c = true;
d = null;
e = new Set();
f = new Map();
g = undefined;
h = NaN;
i = Symbol('1212');
j = {
k: 1
}
constructor() {
this.e.add(1);
this.f.set('z', 1);
}
}
let stringifyVisualbleInstance = new stringifyVisualble();
let stringifyVisualbleStr = JSON.stringify(stringifyVisualbleInstance);
console.log(stringifyVisualbleStr);
打印结果为
{"a":"123","c":true,"d":null,"e":{},"f":{},"h":null,"j":{"k":1}}
重写toJSON
class TOJSON {
a = 1;
toJSON() {
return { b: 2};
}
}
console.log(JSON.stringify(new TOJSON()))
打印结果
{"b":2}
stringify 的 replacer的使用
stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string;
class Replacer{
a = 1;
b = 2;
c = {
a: 3,
d: 4
}
}
console.log(JSON.stringify(new Replacer(), ['a','c']));
打印结果
{"a":1,"c":{"a":3}}
stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string;
class Replacer{
a = 1;
b = 2;
c = {
a: 3,
d: 4
}
}
console.log('结果',(<any>JSON.stringify)(new Replacer(), (target: any, key: any, value: any) => {
console.log(target)
console.log(key);
console.log(value);
let b = '1';
return 'res';
}));
打印结果很奇怪,和lib.es5.d.ts中的定义不一致,还需要再了解了解
Replacer { a: 1, b: 2, c: { a: 3, d: 4 } }
undefined
结果 "res"
space
class Replacer{
a = 1;
b = 2;
c = {
a: 3,
d: 4
}
}
console.log(JSON.stringify(new Replacer(), undefined, '-'))
打印结果
{
-"a": 1,
-"b": 2,
-"c": {
--"a": 3,
--"d": 4
-}
}
可以使用制表符’\t’,实现换行