详解JSON

103 阅读1分钟

JSON(会过滤掉函数、特殊字符)[会实现深拷贝]

const obj = {
  name: 'SharkDog',
  age: 18,
  friends: [
    '苏苏',
    '土狗',
    '安安'
  ],
  test() {
    return '我在序列化时会被过滤掉的因为JSON不能存储函数如果硬是想保存就传入第二个函数拦截一下转成字符串'
  }
};

// 普通序列化
console.log(JSON.stringify(obj));

// 只序列化指定字段
console.log(JSON.stringify(obj, ['name', 'friends']));

// 序列化时对字段做处理
const json = JSON.stringify(obj, (key, value) => {
  // 必须要return否则会被过滤掉
  if (key == 'age') return value + 4;
  if (key == 'name') return value = '土狗';

  return value;
})
console.log(json);

// 第三个参数(转化后换行并缩进指定空格数)[如果传的是字符串则会根据字符串进行缩进]
console.log(JSON.stringify(obj, null, 2));

// 被序列化的对象实现了toJSON函数时
const toJSONObj = {
  test: 'test',
  toJSON() {
    return '如果被序列化对象中包含toJSON函数则最后的结果就是toJSON函数的返回值'
  }
};
console.log(JSON.stringify(toJSONObj));

// 对JSON字符串解析
console.log(JSON.parse(json));

// 解析时传入第二个参数
console.log(JSON.parse(json, (key, value) => {
  if (key == 'age') return value = 18;
  if (key == 'name') return value = '苏苏';
  // 返回undefined时将会过滤掉指定key
  if (key == 'friends') return undefined;

  return value;
}));