JSON.stringify
Sunny-117 opened this issue · 2 comments
Sunny-117 commented
function toJSON(data){
}
// test
toJSON(""); // -> ""
toJSON("abc"); // -> "abc"
toJSON(123); // -> 123
toJSON({a:1, b:2}); // -> {"a":1, "b":2}
toJSON(["1", 3, {name:"monica", age:18}]); //-> ["1", 3, {"name":"monica", "age":18}]
kangkang123269 commented
function toJSON(obj) {
if (typeof obj === 'string') {
return `"${obj}"`;
}
if (typeof obj === 'number' || typeof obj === 'boolean' || obj === null) {
return String(obj);
}
if (Array.isArray(obj)) {
return `[${obj.map(item => toJSON(item)).join(',')}]`;
}
if (typeof obj === 'object') {
const keys = Object.keys(obj);
return `{${keys.map(key => `"${key}":${toJSON(obj[key])}`).join(',')}}`;
}
return undefined;
}
Aurora-GSW commented
JSON.myStringify = function (e) {
if (typeof e === 'number' || typeof e === 'boolean' || e === null) return String(e)
if (typeof e === 'string') return `"${e}"`
if (e !== e) return null
if (e.constructor === RegExp) return '{}'
if (e.constructor === Date) return `"${e.toString()}"`
if (Array.isArray(e)) {
return `[${e.map(item=>JSON.myStringify(item)).join(',')}]`
}
if (typeof e === 'object') {
return `{${Object.keys(e).map(item=>`"${item}":${JSON.stringify(e[item])}`).join(',')}}`
}
return undefined
}