Published at
Updated at
Reading time
1min
This post is part of my Today I learned series in which I share all my web development learnings.

I was reading this great article on JSON.stringify by Valeri Karpov when I discovered something I didn't know.

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 it 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. ๐Ÿ‘Œ

Result of running "node tojson.js" showing the applied "toJSON" method.

If you want to learn more you can check MDN or have a look at a chapter of Exploring JavaScript written by Axel Rauschmayer.

If you enjoyed this article...

Join 5.5k readers and learn something new every week with Web Weekly.

Web Weekly โ€” Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles