JSON.parse JSON.stringify

554 阅读1分钟

JSON.parse第二个参数

JSON.parse(JSON.stringify({
  name"tom",
  age18,
  phone"15888787788",
  IDCard"xxxx"
}), (key, value)=>{
  if(key === "IDCard"){
    return undefined
  }
  return value;
});   // {name: "tom", age: 18, phone: "15888787788"}

JSON.parse转换的时候,是深度优先遍历;最后一条key的值,是空值

JSON.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}'(key, value) => {
  console.log(key); // log the current property name, the last is "".
  return value;     // return the unchanged property value.
});
// 1
// 2
// 4
// 6
// 5
// 3
// ""

JSON.stringify(obj, replacer)。 如果replacer是一个函数,则在序列化过程中,被序列化的值的每个属性都会经过该函数的转换和处理;如果该参数是一个数组,则只有包含在这个数组中的属性名才会被序列化到最终的 JSON 字符串中; 如果该参数为 null 或者未提供,则对象所有可枚举属性都会被序列化。

JSON.stringify(foo, ['week', 'month']);
// '{"week":45,"month":7}', 只保留 “week” 和 “month” 属性值。

如果一个被序列化的对象拥有 toJSON 方法,那么该 toJSON 方法就会覆盖该对象默认的序列化行为:不是该对象被序列化,而是调用 toJSON 方法后的返回值会被序列化

var obj = {
  foo: 'foo',
  toJSON: function () {
    return 'bar';
  }
};
JSON.stringify(obj);      // '"bar"'
JSON.stringify({x: obj}); // '{"x":"bar"}'