Monday, April 16, 2018

Custom - toJSON

Example I:


See the below example to understand custom toJson concepts. (Built in toJSON)

let Test = {
  number: 23
};

let TestingDate = {
  title: "DateTest",
  date: new Date(Date.UTC(2018, 0, 1)),
  Test
};

alert( JSON.stringify(TestingDate) );
/*
  {
    "title":"DateTest",
    "date":"2018-01-01T00:00:00.000Z",  // (1)
    "Test": {"number":23}               // (2)
  }
*/

Explanation:

        Here Date is showing perfectly after json convert. Because all dates have a built-in toJSON method which returns the correct string.

Example II: (custom toJSON)




let CustomCheck = {
  number: 23,
  toJSON() {
    return this.number;
  }
};

let CustomCheckTest = {
  title: "Something",
  CustomCheck
};

alert( JSON.stringify(CustomCheck) ); // 23

alert( JSON.stringify(CustomCheckTest) );
/*
  {
    "title":"Something",
    "CustomCheck": 23
  }
*/

Explanation:

This example is different, as we have mentioned toJSON separately. Means, we are not using in built toJSON.

In the initial customCheck object we have returned the number 23. So whenever you are using CustomCheck object , it will provide you 23.






No comments:

Post a Comment