JSON对象
JSON对象有两个方法,stringify()
和parse()
分别是将js序列化为JSON字符串和将JSON 转化为原生js值
let book = {
'name':'names',
money:12,
anthors:{
year:2101,
age:12,
},
edtion:1
}
let jsonBook = JSON.stringify(book)
let parseBook =JSON.parse(jsonBook)
console.log(book);
//anthors: {year: 2101, age: 12}
//edtion: 1
//money: 12
//name: "names"
console.log(jsonBook);
//{"name":"names","money":12,"anthors":{"year":2101,"age":12},"edtion":1}
JSON.stringify()除了实例化对象还可以接收三个参数,第一个参数是过滤器,第二个参数可以是数字或者函数
第二个参数是传的包含字符串的数组的话,JSON字符串返回的是对应的属性
数组
let book = {
'name':'names',
money:12,
anthors:{
year:2101,
age:12,
},
edtion:1
}
let jsonBook = JSON.stringify(book,['money','edtion'])
console.log(jsonBook);
//{"money":12,"edtion":1}
函数
函数接受两个参数key和value,我们可以对应key相应的属性执行操作,
值得注意的是 return undefined 会忽略我的属性,最后在default时候一定要返回我们的value
let book = {
name:[
'name','name1','name2'
],
money: 12,
anthors: {
year: 2101,
age: 12,
},
edtion: 1,
};
let jsonBook = JSON.stringify(book, (key, value) => {
switch (key) {
case "name":
return value.join(",");
case "money":
return 5000;
case "anthors":
return undefined
default:
return value
}
});
console.log(jsonBook);
//{"name":"name,name1,name2","money":5000,"edtion":1}
第三个参数 缩进
除了可以传入数字也可以传入字符串
let jsonBook = JSON.stringify(book,null,'--')
let book = {
name:[
'name','name1','name2'
],
money: 12,
anthors: {
year: 2101,
age: 12,
},
edtion: 1,
};
let jsonBook = JSON.stringify(book,null,4)
console.log(jsonBook);
// {
// "name": [
// "name",
// "name1",
// "name2"
// ],
// "money": 12,
// "anthors": {
// "year": 2101,
// "age": 12
// },
// "edtion": 1
// }
{
// --"name": [
// ----"name",
// ----"name1",
// ----"name2"
// --],
// --"money": 12,
// --"anthors": {
// ----"year": 2101,
// ----"age": 12
// --},
// --"edtion": 1
// }
网友评论