JSON.stringify

语法

JSON.stringify(value[, replacer [, space]])
  • value:将要序列化成 一个 JSON 字符串的值
  • replacer:如果该参数是一个函数,则在序列化过程中,被序列化的值的每个属性都会经过该函数的转换和处理;如果该参数是一个数组,则只有包含在这个数组中的属性名才会被序列化到最终的 JSON 字符串中;如果该参数为 null 或者未提供,则对象所有的属性都会被序列化。
  • space:指定缩进用的空白字符串,美化输出。

举例

如下代码所示,演示了JSON.stringify的用法。

当传入第2个参数,且是一个函数时,被序列化的每个属性都会经过函数的转化。函数有两个参数:keyvalue,这里对value进行了aA的操作。

当传入第2个参数,且是一个数组时,只有在这个数组中的属性名才会被返回。这里acd被返回。

当传入第3个参数,这里传入了两个空格,起到美化输出的作用。

const obj = {
  a: 'a',
  b: 'b',
  c: {
    d: 'd'
  }
};

// 简单使用
console.log(JSON.stringify(obj));
// {"a":"a","b":"b","c":{"d":"d"}}

// 传入replacer,为函数
console.log(
  JSON.stringify(obj, (key, value) => {
    if (value === 'a') {
      return 'A';
    }
    return value;
  })
);
// {"a":"A","b":"b","c":{"d":"d"}}

// 传入replacer,为数组
console.log(JSON.stringify(obj, ['a', 'c', 'd']));
// {"a":"a","c":{"d":"d"}}

// 传入space,美化输出
console.log(JSON.stringify(obj, null, '  '));
// {
//   "a": "a",
//   "b": "b",
//   "c": {
//     "d": "d"
//   }
// }

安全问题

数据丢失

(1)Date对象拷贝后,变成字符串

const obj = {
  a: new Date()
};

console.log(JSON.stringify(obj));
// {"a":"2022-04-01T08:40:48.781Z"}

(2)正则、Error对象拷贝后,变成空对象

const obj = {
  a: /[123]/g,
  b: new Error('err')
};

console.log(JSON.stringify(obj));
// {"a":{},"b":{}}

(3)函数、undefined属性、Symbol属性拷贝后属性丢失

const obj = {
  a: console.log,
  b: undefined,
  c: Symbol('123')
};

console.log(JSON.stringify(obj));
// {}

(4)NaNInfinity-Infinity拷贝后变成null

const obj = {
  a: NaN,
  b: Infinity,
  c: -Infinity
};

console.log(JSON.stringify(obj));
// {"a":null,"b":null,"c":null}

(5)改变对象的原型链

function A() {
  this.a = 'a';
}

const a = new A();
const b = JSON.parse(JSON.stringify(a));

console.log(a.constructor, b.constructor);
// [Function: A] [Function: Object]

循环引用报错

const a = {
  a: 'a'
};

const b = {
  b: 'b'
};

a.next = b;
b.pre = a;

console.log(JSON.parse(JSON.stringify(a)));
// TypeError: Converting circular structure to JSON

JSON.parse

语法

JSON.parse(text[, reviver])
  • text:要被解析成 JavaScript 值的字符串
  • reviver:转换器,如果传入该函数,可以用来修改解析生成的原始值,调用时机在parse函数返回之前

举例

如下代码所示,传入第二个参数,对value进行处理,处理完再返回。

const str = '{"a":1,"b":2,"c":3}';

// 简单使用
console.log(JSON.parse(str));
// { a: 1, b: 2, c: 3 }

// 传入reviver,处理value
console.log(
  JSON.parse(str, (key, value) => {
    if (key === '') return value;
    return 2 * value;
  })
);
//{ a: 2, b: 4, c: 6 }

兼容性问题

支持主流浏览器。

抢沙发
头像
提交
头像

昵称

取消
昵称图片

    暂无评论内容