Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

JSON.stringify

Sunny-117 opened this issue · comments

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}]
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;
}
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
}