示例工程 20-network-storage-fetch

20-network-storage-fetch/06-json-losses/main.js

javascript · 1.2 KB

运行:20 · JSON 失真

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

// main.js —— JSON 往返的七种失真
export function inspect(value) {
  try {
    const text = JSON.stringify(value);
    return {
      ok: true,
      text,
      revived: text === undefined ? undefined : JSON.parse(text),
    };
  } catch (error) {
    return { ok: false, error: error.name, message: error.message };
  }
}
 
export function run(log = console.log) {
  const circular = {};
  circular.self = circular;
 
  const cases = [
    ['对象里的 undefined', { a: undefined, b: 1 }],
    ['数组里的 undefined/函数/Symbol', [undefined, () => {}, Symbol('s')]],
    ['Date', new Date('2026-01-01T00:00:00.000Z')],
    ['NaN / Infinity', { nan: NaN, inf: Infinity }],
    ['-0', { zero: -0 }],
    ['Map / Set', { map: new Map([['k', 1]]), set: new Set([1]) }],
    ['BigInt', { big: 1n }],
    ['循环引用', circular],
    ['自定义 toJSON', { toJSON: () => ({ x: 1 }) }],
  ];
 
  const rows = [];
  for (const [label, value] of cases) {
    const result = inspect(value);
    rows.push({ label, ...result });
    log(`${label} => ${result.ok ? result.text : `${result.error}: ${result.message}`}`);
  }
  log('要点:JSON 只支持 null/布尔/数字/字符串/数组/普通对象;其余会被丢弃、转换或抛错。');
  return rows;
}