Skip to content

22. 实现 JSON.stringify

js
function jsonStringify(data) {
  let type = typeof data;
  if (type !== 'object' || type === null) {
    if (/string|undefined|function/.test(type)) {
      data = `"${data}"`;
    }
    return String(data);
  } else {
    let json = [];
    let arr = Array.isArray(data);
    for (let k in data) {
      let v = data[k];
      let type = typeof v;
      if (/string|undefined|function/.test(type)) {
        v = `"${v}"`;
      } else if (type === 'object') {
        v = jsonStringify(v);
      }
      json.push((arr ? '' : `"${k}":`) + String(v));
    }
    return (arr ? '[' : '{') + String(json) + (arr ? ']' : '}');
  }
}