javascript / intermediate
Snippet
Safe JSON Serialization with toJSON
Control how objects are converted to JSON strings by defining a toJSON method. This is a best practice for automatically excluding sensitive data like internal hashes or passwords when sending objects to a client or logging them.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
const user = {id: 42,username: 'dev_master',passwordHash: 'sha256$e92a...',lastLogin: new Date(),toJSON() {const { passwordHash, ...publicData } = this;return publicData;}};console.log(JSON.stringify(user));// Output: {"id":42,"username":"dev_master","lastLogin":"..."}
nodejs
Breakdown
1
toJSON() {
A special method recognized by JSON.stringify to customize the serialized output.
2
const { passwordHash, ...publicData } = this;
Uses object destructuring and rest syntax to extract everything except the sensitive property.
3
return publicData;
Returns the modified object that will actually be used for the JSON string.