-3

Why Angular2 override JSON.stringify !?

I have override my own Date.toJSON but it's not called when stringify an object.

In the following exemple it's work correctly, but it doesn't work in Angular App !

<html>
  
  <body>
    
    Custom Date Fomat : <span id="date1"></span><br>
    ISO Date Format : <span id="date2"></span>
  
  </body>
  
  <script>
    Date.prototype.toJSON = function(){
      var day = date.getDate();
      var month = date.getMonth() + 1;
      var year = date.getFullYear();

      var s =  year + "-" + 
        (month > 9 ? "" : "0") + month + "-" + 
        (day   > 9 ? "" : "0") + day   + "T00:00:00.000Z";

      return s;
    }
  
    var date = new Date();
    document.getElementById("date1").innerHTML = JSON.stringify({date});
    document.getElementById("date2").innerHTML = date.toISOString();
  
  </script>

</html>
usf
  • 1
  • 2

1 Answers1

1

JSON.stringify will only copy properties that are the objects ‘own’ properties – ie the ‘top level’ properties of that object. If you have a complex javascript object using prototypical inheritance, it will NOT copy properties that are from the prototype chain.

Basically once you’re dealing with objects of a specific type (created with function constructors), you can’t trust that JSON.stringify will do what you expect. The JSON specifications do allow custom objects like this to provide their own .toJson() method, which JSON.stringify will use. However not all library vendors (or browser vendors) bother to provide this feature.

Luckily the workaround is pretty simple. You can provide/attach your own .toJson() method, or ‘copy’ the object’s properties yourself into a pojo (plain old javascript object) as soon as you receive the object. Once you’re dealing with a pojo, JSON.stringify works wonderfully. But be careful that ALL of the child properties of the object are copied over as native data types or pojos.

Lakshmi Swetha G
  • 2,691
  • 1
  • 9
  • 13