• 使用JSON.stringify()进行对象转字符串需要注意的陷进
  • 发布于 1个月前
  • 59 热度
    0 评论
JavaScript 中的 JSON.stringify() 是一个强大的函数,用于将 JavaScript 对象转换为 JSON 格式的字符串。然而,它也带来了一些细微差别和潜在的陷阱,大家需要注意以避免意外的行为。在本文中,我们将探讨与 JSON.stringify() 相关的各种陷阱。

1.处理未定义的、函数和符号值:
一个值得注意的限制是未定义,函数和符号值不是有效的 JSON 值。在转换过程中遇到时,它们要么被省略(在对象中),要么被更改为 null(在数组中)。这可能会导致意外的结果,例如函数被替换为 null。

示例:
const obj = { foo: function() {},
             bar: undefined, 
             baz: Symbol('example') };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // Output: '{"foo":null}'

const obj2 = {arr: [function(){}]};
console.log(JSON.stringify(obj2)); // Output: {"arr":[null]}
2.布尔、数字和字符串对象的原始值
布尔、数字和字符串对象在字符串化过程中被转换为它们相应的原始值。这与传统的转换语义一致。
示例:
const boolObj = new Boolean(true);
const jsonString = JSON.stringify(boolObj);
console.log(jsonString); // Output: 'true'
3.忽略符号键属性:
符号键控的属性在字符串化过程中被完全忽略,即使使用替换器函数。这意味着与 Symbol 键关联的任何数据都将从生成的 JSON 字符串中排除。
示例:
const obj = { [Symbol('example')]: 'value' };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // Output: '{}'

const obj2 = {arr: [function(){}]};
console.log(JSON.stringify(obj2)); // Output '{}'
4.处理 Infinity、NaN 和 Null 值:
Infinity、NaN 和 null 值在字符串化期间都被视为 null。

示例:
const obj = { value: Infinity, 
             error: NaN, 
             nothing: null };
const jsonString = JSON.stringify(obj);
console.log(jsonString); 
// Output: '{"value":null,"error":null,"nothing":null}'
5.toJSON() 方法职责:
如果一个对象有一个 toJSON() 方法,它负责定义哪些数据将被序列化。这允许对象的自定义序列化逻辑。

示例:
const obj = {
    data: 'important information',
    toJSON: function () {
        return { customKey: this.data };
    },
};
const jsonString = JSON.stringify(obj);
console.log(jsonString);
// Output: '{"customKey":"important information"}'
6.日期对象作为字符串处理:
Date 的实例通过返回一个字符串(与 date.toISOString() 相同)来实现 toJSON() 函数,从而在字符串化期间将其视为字符串。
示例:
const dateObj = new Date();
const jsonString = JSON.stringify(dateObj);
console.log(jsonString); 
// Output: '"2023–12–06T12:34:56.789Z"'
7.循环引用异常:
如果 JSON.stringify() 遇到循环引用的对象,它将抛出错误。当一个对象在循环中引用自身时,就会发生循环引用。

示例:
const circularObj = { self: null };
circularObj.self = circularObj;
JSON.stringify(circularObj); // Throws an error
8.可枚举属性的序列化:
对于像 Map、Set、WeakMap 和 WeakSet 这样的 Object 实例,只有它们的可枚举属性才会被序列化。不可枚举的属性被排除在外。
示例:
const mapObj = new Map([['key', 'value']]);
const jsonString = JSON.stringify(mapObj);
console.log(jsonString); // Output: '{}'
9.BigInt 转换时出错:
尝试使用 JSON.stringify() 转换 BigInt 类型的值时,会抛出错误。
示例:
const bigIntValue = BigInt(42); //堆代码 duidaima.com
JSON.stringify(bigIntValue); // Throws an error
结论:
了解 JSON.stringify() 的细微差别对于防止 JavaScript 代码中出现意外问题至关重要。通过了解这些陷阱,大家可以更有效地使用此函数并避免项目中的常见错误。
用户评论