JSON.stringify()学习笔记
1. 简介
JSON.stringify()
是 JavaScript 中一个用于将 JavaScript 对象转换为 JSON 字符串的方法。它接受三个参数:要转换的对象、可选的替换函数和可选的缩进空格数。
2. 实例
假设我们有以下 JavaScript 对象:
javascriptCopy Codeconst obj = {
name: "Tom",
age: 20,
hometown: {
city: "Shanghai",
country: "China"
},
hobbies: ["reading", "running", "coding"]
};
我们可以使用 JSON.stringify()
将其转换为 JSON 字符串:
javascriptCopy Codeconst jsonStr = JSON.stringify(obj);
console.log(jsonStr);
// 输出结果:{"name":"Tom","age":20,"hometown":{"city":"Shanghai","country":"China"},"hobbies":["reading","running","coding"]}
如果我们想要输出格式化后的 JSON 字符串,可以添加第三个参数来指定缩进空格数:
javascriptCopy Codeconst formattedJsonStr = JSON.stringify(obj, null, 2);
console.log(formattedJsonStr);
// 输出结果:
// {
// "name": "Tom",
// "age": 20,
// "hometown": {
// "city": "Shanghai",
// "country": "China"
// },
// "hobbies": [
// "reading",
// "running",
// "coding"
// ]
// }
另外,如果我们想要排除某些属性,可以添加第二个参数来指定替换函数:
javascriptCopy Codeconst filteredJsonStr = JSON.stringify(obj, (key, value) => {
if (key === "hobbies") {
return undefined;
} else {
return value;
}
}, 2);
console.log(filteredJsonStr);
// 输出结果:
// {
// "name": "Tom",
// "age": 20,
// "hometown": {
// "city": "Shanghai",
// "country": "China"
// }
// }
3. 注意事项
JSON.stringify()
只能序列化对象、数组、字符串、数值、布尔值和 null,不能序列化函数、日期、正则表达式等类型。- 如果对象中包含循环引用(即对象 A 中引用了对象 B,而对象 B 再次引用了对象 A),则会抛出错误。
- JSON 字符串必须使用双引号而不是单引号。