JS

梗概

  • 将一个JavaScript对象转换为JSON字符串
    • 会深度转换,对象中引用的其他对象也会被转换

实例:

var json = JSON.stringify({name: "qiulina", age: "3", sex: "女"});
 //结果是 {"name":"qiulina","age":"3","sex":"女"}

不能转换为Json字符串的情况

函数

函数在序列化时会被直接忽略。

const obj = {
  name: 'John',
  greet: function() {
    console.log('Hello');
  }
};
JSON.stringify(obj); // 输出: '{"name":"John"}'

包含 undefined 的值

对象属性值若为 undefined,在序列化时会被跳过;数组中的 undefined 会被转为 null。

const obj = {
  a: undefined,
  b: 'value'
};
JSON.stringify(obj); // 输出: '{"b":"value"}'
const arr = [undefined, 'value'];
JSON.stringify(arr); // 输出: '[null,"value"]'

Symbol 类型

无论是作为键还是值,Symbol 类型都会被忽略。

const obj = {
  [Symbol('key')]: 'value',
  key: Symbol('value')
};
JSON.stringify(obj); // 输出: '{}'

循环引用

对象之间若存在循环引用,会引发错误。

const obj1 = {};
const obj2 = { ref: obj1 };
obj1.ref = obj2; // 循环引用
JSON.stringify(obj1); // 抛出错误: TypeError: Converting circular structure to JSON

特殊对象

像 Error、Date、Map、Set 等特殊对象,在序列化时会有特殊处理。

const date = new Date();
JSON.stringify(date); // 输出: '"2025-06-20T00:00:00.000Z"'(转为 ISO 字符串)
const error = new Error('Error');
JSON.stringify(error); // 输出: '{}'(Error 对象的属性会被忽略)

BigInt 类型

BigInt 类型会导致错误,因为它无法精确地用 JSON 表示。

const num = BigInt(9007199254740991);
JSON.stringify(num); // 抛出错误: TypeError: Do not know how to serialize a BigInt

处理方法

若要对包含上述类型的数据进行序列化,可以借助 JSON.stringify() 的第二个参数 replacer 来自定义序列化规则。

const obj = {
  a: undefined,
  b: function() {},
  c: new Date()
};
const json = JSON.stringify(obj, (key, value) => {
  if (typeof value === 'function') {
    return value.toString(); // 将函数转为字符串
  }
  if (value instanceof Date) {
    return value.getTime(); // 将日期转为时间戳
  }
  return value;
});
console.log(json); // 输出: '{"b":"function() {}","c":1740000000000}'

通过了解这些限制并运用适当的处理方法,就能更妥善地处理复杂数据的序列化问题。