This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis
I was reading this great article on JSON.stringify
by Valeri Karpov when I discovered something I didn't know before.
You can use JSON.stringify
to serialize objects and store them let's say in localStorage
. It turns out that JSON.stringify
checks if the object to serialize includes a toJSON
method. If it does it will use this method to evaluate the result of the serialization.
const zoo = {
animals: {
list: ['cat', 'dog', 'duck'],
// toJSON will be called by JSON.stringify
toJSON: () => {
return ['?', '?', '?']
}
}
}
console.log(JSON.stringify(zoo, null, 2));
By including a toJSON
method you can manipulate the data that should go into serialization. You can use this functionality to e.g. clean up logs and not store sensitive information in a database. Pretty sweet. ?
If you want to learn more you can check MDN or have a look at a chapter of Exploring JavaScript written by Axel Rauschmayer.
Reply to Stefan
This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis

Stefan Judis | Sciencx (2019-06-03T22:00:00+00:00) JSON.stringify takes toJSON methods into consideration (#tilPost). Retrieved from https://www.scien.cx/2019/06/03/json-stringify-takes-tojson-methods-into-consideration-tilpost/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.