https://www.bilibili.com/video/av77733273?p=41
文章目录
# 对象 to JSON
let hd = {
title: '后盾人' ,
url: 'houdunren.com',
teacher: {
name: '向军大叔'
}
}
let json = JSON.stringify(hd , ['title','url'],2) ;
console.log(json) ;
let hd = {
title: '后盾人' ,
url: 'houdunren.com',
teacher: {
name: '向军大叔'
}
}
let json = JSON.stringify(hd , null,2) ;
console.log(json) ;
# 数组
let arr = ['后盾人','hdcms.com'] ;
let json = JSON.stringify(arr , ['title','url'],2) ;
console.log(json) ;
let arr = ['后盾人','hdcms.com'] ;
let json = JSON.stringify(arr , null ,2) ;
console.log(json) ;
let r = JSON.parse(json);
console.log(r)
# 自定义 toJSON
let hd = {
title: '后盾人' ,
url: 'houdunren.com',
teacher: {
name: '向军大叔'
},
toJSON: function() {
return {
title: this.title,
teacher: this.teacher.name
}
}
}
let json = JSON.stringify(hd , null,2) ;
console.log(json) ;
<mark>toJSON: 可以看成 stringify 第二个参数</mark>
解析
let hd = {
title: '后盾人' ,
url: 'houdunren.com',
teacher: {
name: '向军大叔'
},
toJSON: function() {
return {
title: this.title,
teacher: this.teacher.name
}
}
}
let json = JSON.stringify(hd,null,2) ;
console.log(json) ;
let obj = JSON.parse(json , (key,value) => {
if(key == 'title') {
value = `[后盾]-${value}`;
}
return value ;
}) ;
console.log(obj.title) ;