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) => {
if (key == 'age') return value + 4;
if (key == 'name') return value = '土狗';
return value;
})
console.log(json);
console.log(JSON.stringify(obj, null, 2));
const toJSONObj = {
test: 'test',
toJSON() {
return '如果被序列化对象中包含toJSON函数则最后的结果就是toJSON函数的返回值'
}
};
console.log(JSON.stringify(toJSONObj));
console.log(JSON.parse(json));
console.log(JSON.parse(json, (key, value) => {
if (key == 'age') return value = 18;
if (key == 'name') return value = '苏苏';
if (key == 'friends') return undefined;
return value;
}));