Skip to content

36.请举例说明JSON.stringify()有哪些特性? #36

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
webVueBlog opened this issue Mar 14, 2020 · 0 comments
Open

36.请举例说明JSON.stringify()有哪些特性? #36

webVueBlog opened this issue Mar 14, 2020 · 0 comments
Labels
JavaScript JavaScript

Comments

@webVueBlog
Copy link
Member

JSON.stringify() 九大特性

JSON.stringify()第一大特性

对于 undefined、任意的函数以及 symbol 三个特殊的值分别作为对象属性的值、数组元素、单独的值时 JSON.stringify()将返回不同的结果。

const data = {
  a: "aaa",
  b: undefined,
  c: Symbol("dd"),
  fn: function() {
    return true;
  }
};
JSON.stringify(data); // 输出:?

// "{"a":"aaa"}"
  • undefined、任意的函数以及 symbol 作为对象属性值时 JSON.stringify() 将跳过(忽略)对它们进行序列化

假设 undefined、任意的函数以及 symbol 值作为数组元素会是怎样呢?

JSON.stringify(["aaa", undefined, function aa() {
    return true
  }, Symbol('dd')])  // 输出:?

// "["aaa",null,null,null]"

undefined、任意的函数以及 symbol 作为数组元素值时,JSON.stringify() 会将它们序列化为 null

JSON.stringify(function a (){console.log('a')})
// undefined
JSON.stringify(undefined)
// undefined
JSON.stringify(Symbol('dd'))
// undefined

undefined、任意的函数以及 symbol 被 JSON.stringify() 作为单独的值进行序列化时都会返回 undefined

JSON.stringify() 第二大特性

非数组对象的属性不能保证以特定的顺序出现在序列化后的字符串中。

const data = {
  a: "aaa",
  b: undefined,
  c: Symbol("dd"),
  fn: function() {
    return true;
  },
  d: "ddd"
};
JSON.stringify(data); // 输出:?
// "{"a":"aaa","d":"ddd"}"

JSON.stringify(["aaa", undefined, function aa() {
    return true
  }, Symbol('dd'),"eee"])  // 输出:?

// "["aaa",null,null,null,"eee"]"

JSON.stringify() 第三大特性

转换值如果有 toJSON() 函数,该函数返回什么值,序列化结果就是什么值,并且忽略其他属性的值。

JSON.stringify({
    say: "hello JSON.stringify",
    toJSON: function() {
      return "today i learn";
    }
  })
// "today i learn"

JSON.stringify()第四大特性

JSON.stringify() 将会正常序列化 Date 的值。

JSON.stringify({ now: new Date() });
// "{"now":"2019-12-08T07:42:11.973Z"}"

实际上 Date 对象自己部署了 toJSON() 方法(同Date.toISOString()),因此 Date 对象会被当做字符串处理。

JSON.stringify() 第五大特性

NaN 和 Infinity 格式的数值及 null 都会被当做 null。

直接上代码:

JSON.stringify(NaN)
// "null"
JSON.stringify(null)
// "null"
JSON.stringify(Infinity)
// "null"

JSON.stringify() 第六大特性

布尔值、数字、字符串的包装对象在序列化过程中会自动转换成对应的原始值。

JSON.stringify([new Number(1), new String("false"), new Boolean(false)]);
// "[1,"false",false]"

JSON.stringify() 第七大特性

其他类型的对象,包括 Map/Set/WeakMap/WeakSet,仅会序列化可枚举的属性。

// 不可枚举的属性默认会被忽略:
JSON.stringify( 
    Object.create(
        null, 
        { 
            x: { value: 'json', enumerable: false }, 
            y: { value: 'stringify', enumerable: true } 
        }
    )
);
// "{"y":"stringify"}"

JSON.stringify() 第八大特性

实现深拷贝最简单粗暴的方式就是序列化:JSON.parse(JSON.stringify()),这个方式实现深拷贝会因为序列化的诸多特性从而导致诸多的坑点

JSON.stringify() 第九大特性
所有以 symbol 为属性键的属性都会被完全忽略掉,即便 replacer 参数中强制指定包含了它们。

JSON.stringify({ [Symbol.for("json")]: "stringify" }, function(k, v) {
    if (typeof k === "symbol") {
      return v;
    }
  })

// undefined

JSON.stringify

var obj = {
 name: 'Jeskson',
 age: 12,
};

var json = JSON.stringify(obj);
// {"name":"Jeskson","age":12}

// {"name":"Jeskson","age":12}
console.log(JSON.stringify(obj,["name","age"]));
  1. JSON.stringify
let foo = { a: 2, b: function() {} };JSON.stringify(foo);// "{ "a": 2 }"

JSON.stringify函数将一个 JavaScript 对象转换成文本化的 JSON。不能被文本化的属性会被忽略。foo中属性b的值是函数定义,没有被转换而丢失。

@webVueBlog webVueBlog added the JavaScript JavaScript label Mar 14, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript JavaScript
Projects
None yet
Development

No branches or pull requests

1 participant