-
Notifications
You must be signed in to change notification settings - Fork 6
Open
Labels
Description
主要思路是递归
var toStringify = json => {
switch(typeof json) {
case 'undefined':
return ""
case 'string':
return `"${json}"`
case 'number':
return `${json}`;
case 'boolean':
return json ? "true" : "false"
default:
if(json === null) {
return "null";
}else if(Array.isArray(json)) {
return `[${json.map(toStringify).join(',')}]`
} else {
return `{${Object.keys(json).map(key => `"${key}":${toStringify(json[key])}`).join(',')}}`
}
}
}
var json = {
x: 1,
y: [1, "str", true, { name: 'yiyi'}],
z: {
a: 1,
b: null
}
};
var s = JSON.stringify(json);
var s1 = stringify(json);
var s2 = toStringify(json);
console.log(s); // {"x":1,"y":[1,"str",true,{"name":"yiyi"}],"z":{"a":1,"b":null}}
console.log(s2); // {"x":1,"y":[1,"str",true,{"name":"yiyi"}],"z":{"a":1,"b":null}}
console.log(JSON.parse(s2));