JSON.stringify()

参考JSON.stringify()

此方法将一个js对象转为JSON字符串

参数:JSON.stringify(value[, replacer [, space]])

返回值 JSON字符串

value的各种情况及返回值
  1. 布尔值、数字、字符串的包装对象在序列化过程中会自动转换成对应的原始值
JSON.stringify([new String('string'), new Number(12), new Boolean(true)])
// '["string",12,true]'
  1. undefined、任意的函数以及 symbol 值,在序列化过程中会被忽略(出现在非数组对象的属性值中时)或者被转换成 null(出现在数组中时)。函数、undefined 被单独转换时,会返回 undefined。所有以 symbol 为属性键的属性都会被完全忽略掉,即便 replacer 参数中强制指定包含了它们。
JSON.stringify([Symbol(""),function test(){return 12}, undefined,null, Object,NaN,Infinity])
// '[null,null,null,null,null,null,null]'
JSON.stringify(function test(){return 12}) // undefined
JSON.stringify(undefined) // undefined
JSON.stringify(Symbol("")) // undefined
JSON.stringify(Object) // undefined
JSON.stringify(null) // 'null'
JSON.stringify(NaN) // 'null'
JSON.stringify(Infinity) // 'null'
const test = {
  fn: function () {
    return 'ss'
  },
  sym: Symbol(''),
  un: undefined,
  nul: null,
  obj: Object,
  str: new String('str'),
  num: new Number(12),
  bool: new Boolean(true)
}
JSON.stringify(test) // '{"nul":null,"str":"str","num":12,"bool":true}'
  1. 对包含循环引用的对象(对象之间相互引用,形成无限循环)执行此方法,会抛出错误。
  2. Date 日期调用了 toJSON() 将其转换为了 string 字符串(同 Date.toISOString()),因此会被当做字符串处理。
JSON.stringify(new Date()) // '"2022-11-28T14:55:41.474Z"'
  1. 他类型的对象,包括 Map/Set/WeakMap/WeakSet,仅会序列化可枚举的属性。
const wrongMap = new Map();
wrongMap['bla'] = 'blaa';
wrongMap['bla2'] = 'blaaa2';
wrongMap.set('we',23)
JSON.stringify(wrongMap) 
// '{"bla":"blaa","bla2":"blaaa2"}'
  1. 不可枚举的属性默认会被忽略
JSON.stringify(
    Object.create(
        null,
        {
            x: { value: 'x', enumerable: false },
            y: { value: 'y', enumerable: true }
        }
    )
);
// "{"y":"y"}"
  1. 如果一个被序列化的对象拥有 toJSON 方法,那么该 toJSON 方法就会覆盖该对象默认的序列化行为:不是该对象被序列化,而是调用 toJSON 方法后的返回值会被序列化
const parentObj = {
      name: 'parent',
      color: 'red',
      toJSON: function () {
        return 'bar';
      }
    };
console.log(JSON.stringify(parentObj, null, '\t'));// "bar"
replacer的各种情况
  1. 函数,如果返回一个指定的值(string.number,boolean)则会作为属性值添加进JSON字符串
const parentObj = {
  name: 'parent',
  color: 'red',
  num: 12,
  bool: true,
  fn: function () {},
  parent: 'parent'
};

function replacer(key, val) {
  if (['name'].includes(key)) {
    return undefined; // 如果为12则返回{"name":12,"color":"red","num":12,"bool":true,"parent":"parent"}
  }
  return val;
}
console.log(JSON.stringify(parentObj)); // {"name":"parent","color":"red","num":12,"bool":true,"parent":"parent"}
console.log(JSON.stringify(parentObj, replacer)); // {"color":"red","num":12,"bool":true,"parent":"parent"}
  1. 数组-如果 replacer 是一个数组,数组的值代表将被序列化成 JSON 字符串的属性名
console.log(JSON.stringify(parentObj, ['name'])); // {"name":"parent"}
space
  1. 为数字时,则在字符串化时每一级别会比上一级别缩进多这个数字值的空格(最多 10 个空格),即设置超过10的数组,永远都是10个空格
const parentObj = {
  name: 'parent',
  color: 'red'
};
console.log(JSON.stringify(parentObj, null, 10));
console.log(JSON.stringify(parentObj, null, 900));

when replace is number

  1. 如果是一个字符串,则每一级别会比上一级别多缩进该字符串(或该字符串的前 10 个字符)
console.log(JSON.stringify(parentObj, null, '1234567890a'));

when replacer is string

console.log(JSON.stringify(parentObj, null, '\t'));

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值