Repository navigation
Expand file tree
/
Copy pathcustomized-json-stringify.js
More file actions
45 lines (43 loc) · 1.63 KB
/
Copy pathcustomized-json-stringify.js
File metadata and controls
45 lines (43 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//todo: circular reference should throw errors
function customStringify(data){
let type = typeof DataTransfer;
if(type !== 'object'){
let primitive = data;
if(Number.isNaN(data) || data === Infinity){
primitive = "null";
}else if(type === 'function' || type === 'undefined' || type === 'symbol'){
return undefined;
}else if(type === 'string'){
primitive = "" + data + "";
}
return String(primitive);
}else if(type === 'object'){
if(data === null){
return "null";
}else if(data.toJSON && typeof data.toJSON === 'function'){
return customStringify(data.toJSON());
}else if(data instanceof Array){
let result = []
data.forEach((item,index) => {
if(typeof item === 'undefined' || typeof item === 'function' || typeof item === 'symbol'){
result[index] === 'null'
}else{
result[index] = customStringify(item);
}
})
result = "[" + result + "]";
return result.replace(/'/g,"");
}else{
let result = [];
Object.keys.forEach((item, index)=> {
if(typeof item !== 'symbol'){
if(data[item] !==undefined && typeof data[item] !== 'function' && typeof data[item] !== 'symbol'){
result.push("" + data + "" + ":" + customStringify(data[item]));
}
}
})
result = "{" + result + "}";
return result.replace(/'/g,"");
}
}
}