Difference between toJSON() and JSON.Stringify()

前端 未结 3 1194
傲寒
傲寒 2020-12-02 13:16

if you need to read or clone all of a model’s data attributes, use its toJSON() method. This method returns a copy of the attributes as an object (not a J

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 13:43

    • JSON.stringify() - Any valid JSON representation value can be stringified.

      The JSON.stringify(..) utility will automatically omit undefined, function, and symbol values when it comes across them. If such a value is found in an array, that value is replaced by null (so that the array position information isn't altered). If found as a property of an object, that property will simply be excluded.

      JSON stringification has the special behavior that if an object value has a toJSON() method defined, this method will be called first to get a value to use for serialization.

    • toJSON() - to a valid JSON value suitable for stringification.

      One example, JSON.stringify() an object with circular reference in it, an error will be thrown. toJSON() can fix it as following.

      var o = { };
      var a = {
          b: 32,
          c: o
      };
      
      // circular reference
      o.d = a;
      
      // JSON.stringify( a ); // an error caused by circular reference
      
      // define toJSON method
      a.toJSON = function() {
           return { b: this.b };
      };
      
      JSON.stringify( a ); // "{"b":32}"
      

提交回复
热议问题