认识 JSON
JSON → JavaScript Object Notation,一种 JavaScript 的对象表示法
JSON 的作用:进行前后端的数据交互
let obj = {
name: 'superman',
age: 18
};
let json = '{"name":"superman","age":18}';
JSON 的方法
parse()
作用:JSON → 对象(英文 parse 是 “解析” 的意思)
JSON.parse(json);
let json = '{"name":"superman", "age":18}';
console.log('json', json); // json {"name":"superman", "age":18}
let obj = JSON.parse(json);
console.log('obj', obj); // obj {name: "superman", age: 18}
stringify()
作用:对象 → JSON(英文 stringify 是 “字符串化” 的意思)
JSON.stringify(obj);
const obj = {
name: "superman",
hobbies: ["basketball", "football"],
age: 21,
};
console.log(JSON.stringify(obj)); // {"name":"superman","hobbies":["basketball","football"],"age":21}
处理特殊属性值:
- 对于对象的特殊属性值:
const obj = {
// 函数 → 直接忽略
_function: function () {
console.log("singing");
},
_undefined: undefined, // undefined → 直接忽略
_null: null, // null → 返回 null
_NaN: NaN, // NaN → 返回 null
_Infinity1: Infinity, // Infinity → 返回 null
_Infinity2: -Infinity, // -Infinity → 返回 null
_RegExp: new RegExp(), // 正则 → 返回空对象 {}
_Date: new Date(), // Date → 以字符串形式返回
};
console.log(JSON.stringify(obj));
// {"_null":null,"_NaN":null,"_Infinity1":null,"_Infinity2":null,"_RegExp":{},"_Date":"2022-08-23T15:14:06.581Z"}
- 对于原型的属性:
function Person(name) {
this.name = name;
}
Person.prototype.age = 21; // 原型的属性 → 直接忽略
const person = new Person("superman");
console.log(JSON.stringify(person)); // {"name":"superman"}
传入更多参数:
const obj = {
name: "superman",
age: 21,
gender: "male",
address: "China",
};
console.log(JSON.stringify(obj, ["name", "gender"])); // {"name":"superman","gender":"male"}
const studentData = [{
name: "张三", score: 90,
}, {
name: "李四", score: 80,
}];
function formatData(key, value) {
if (key === "score") {
switch (true) {
case value >= 90: return "A";
case value >= 80: return "B";
case value >= 70: return "C";
case value >= 60: return "D";
default: return "E";
}
}
return value;
}
console.log(JSON.stringify(studentData, formatData)); // [{"name":"张三","score":"A"},{"name":"李四","score":"B"}]
- 第 3 个参数为数字,表示输出的缩进距离
const obj = {
name: "superman",
hobbies: ["basketball", "football"],
age: 21,
};
console.log(JSON.stringify(obj, null, 4)); // 缩进为 4 个空格
// {
// "name": "superman",
// "hobbies": [
// "basketball",
// "football"
// ],
// "age": 21
// }
自定义:
const obj = {
name: "superman",
hobbies: ["basketball", "football"],
age: 21,
toJSON: function () { // 注意:不能使用 ES6 的简写 `toJSON(){}`
return `${this.name}, ${this.hobbies}, ${this.age}`;
},
};
console.log(JSON.stringify(obj)); // "superman, basketball,football, 21"
使用场景:
- 配合 localStorage 使用:
const obj = { name: "superman" };
localStorage.setItem("obj", JSON.stringify(obj));
const objStr = localStorage.getItem("obj");
- 深拷贝对象:
const obj = {
name: "superman",
hobbies: ["basketball", "football"],
age: 21,
};
const objDeepcopy = JSON.parse(JSON.stringify(obj));
objDeepcopy.hobbies[0] = "swimming";
console.log(obj); // { name: 'superman', hobbies: [ 'basketball', 'football' ], age: 21 }
console.log(objDeepcopy); // { name: 'superman', hobbies: [ 'swimming', 'football' ], age: 21 }
-
JSON.stringify()
不能作用于循环结构的对象:
const obj = {
name: "superman",
};
obj.myObj = obj; // 形成闭环
console.log(JSON.stringify(obj)); // TypeError: Converting circular structure to JSON