请举例说明JSON.stringify()有哪些特性?
JSON.stringify()
用于将 JavaScript 值转换为 JSON 字符串。它有一些重要的特性,以下是一些例子:
1. 基本数据类型的转换:
-
数字、字符串、布尔值: 直接转换为对应的 JSON 类型。
JSON.stringify(10); // "10" JSON.stringify("hello"); // ""hello"" JSON.stringify(true); // "true"
-
null: 转换为
null
。JSON.stringify(null); // "null"
-
undefined: 如果直接作为
JSON.stringify()
的参数,会被忽略;如果在对象中,会被转换为null
(在老版本浏览器中可能会被忽略)。JSON.stringify(undefined); // undefined JSON.stringify({a: undefined}); // "{}" (很多现代浏览器)
2. 数组的转换:
JSON.stringify([1, "hello", true, null]); // "[1,"hello",true,null]"
3. 对象的转换:
const obj = {
name: "John Doe",
age: 30,
city: "New York"
};
JSON.stringify(obj); // "{\"name\":\"John Doe\",\"age\":30,\"city\":\"New York\"}"
4. 函数和 Symbol 会被忽略:
const obj = {
name: "John Doe",
greet: function() { console.log("Hello!"); },
symbol: Symbol('test')
};
JSON.stringify(obj); // "{\"name\":\"John Doe\"}"
5. 循环引用会报错:
const obj1 = {};
const obj2 = {};
obj1.a = obj2;
obj2.b = obj1;
JSON.stringify(obj1); // TypeError: Converting circular structure to JSON
6. 使用第二个参数 replacer 进行过滤或转换:
replacer
可以是数组或函数。
-
数组: 只包含指定属性。
const obj = { name: "John Doe", age: 30, city: "New York" }; JSON.stringify(obj, ["name", "city"]); // "{\"name\":\"John Doe\",\"city\":\"New York\"}"
-
函数: 对每个属性进行自定义转换。
const obj = { name: "John Doe", age: 30 }; JSON.stringify(obj, (key, value) => { if (key === "age") { return value * 2; } return value; }); // "{\"name\":\"John Doe\",\"age\":60}"
7. 使用第三个参数 space 进行格式化:
space
可以是数字或字符串,用于缩进。
const obj = {
name: "John Doe",
age: 30,
city: "New York"
};
JSON.stringify(obj, null, 2);
/*
{
"name": "John Doe",
"age": 30,
"city": "New York"
}
*/
JSON.stringify(obj, null, "\t");
/*
{
"name": "John Doe",
"age": 30,
"city": "New York"
}
*/
这些例子展示了 JSON.stringify()
的一些常见特性,包括基本数据类型、数组、对象、函数、循环引用、replacer
参数和 space
参数的使用。理解这些特性可以帮助你更好地使用 JSON.stringify()
进行数据转换。