JSON序列化与反序列化
一.JSON语法
重点:
1.简单值里面不包括undefined !!!
2.JSON字符串必须使用双引号,单引号会导致语法错误。
3.JSON与JS对象的不同之处:JSON不用声明变量,不用分号结束,属性名必须用双引号包裹。
二,JSON序列化与反序列化
1.JSON.stringify()
const info = {
name: lx,
age: 24,
hobby: [tv, shopping]
}
const jsonText = JSON.stringify(info)
console.log(jsonText) // {"name":"lx","age":24,"hobby":["tv","shopping"]}
JSON.stringify()的第二个参数,相当于过滤器,可以是数组或者函数,数组里有什么就返回什么。
const info = {
name: lx,
age: 24,
hobby: [tv, shopping]
}
// 数组
const jsonText2 = JSON.stringify(info, [name, hobby])
console.log(jsonText2) // {"name":"lx","hobby":["tv","shopping"]}
// 函数
const jsonText3 = JSON.stringify(info, (key, value) => {
switch (key) {
case name:
return lxlx
case hobby:
return value.join()
case age:
return undefined
default:
return value
}
})
console.log(jsonText3) // {"name":"lxlx","hobby":"tv,shopping"}当值为undefined时不显示
JSON.stringify()的第三个参数用来控制缩进,第三个参数可以是数值或者字符串,且不大于10,数值大于10,当成0来处理,字符串大于10,只截取前10位
const info = {
name: lx,
age: 24,
hobby: [tv, shopping]
}
const jsonText3 = JSON.stringify(info, null, 8)
console.log(jsonText3)
{
"name": "lx",
"age": 24,
"hobby": [
"tv",
"shopping"
]
}
const jsonText4 = JSON.stringify(info, null, --)
console.log(jsonText4)
{
--"name": "lx",
--"age": 24,
--"hobby": [
----"tv",
----"shopping"
--]
}
