In JavaScript, the JSON.stringify()
function looks for functions named toJSON
in the object being serialized. If an object has a toJSON
function, JSON.stringify()
calls toJSON()
and serializes the return value from toJSON()
instead.
For example, the below script prints the same thing as JSON.stringify({ answer: 42 })
.
const json = JSON.stringify({
answer: { toJSON: () => 42 }
});
console.log(json); // {"answer":42}
The toJSON()
function is useful for making sure ES6 classes get serialized correctly. For example, suppose you have a custom JavaScript error class.
class HTTPError extends Error {
constructor(message, status) {
super(message);
this.status = status;
}
}
By default, JavaScript isn’t great with serializing errors. The below script prints {"status":404}
, no error message or stack trace.
class HTTPError extends Error {
constructor(message, status) {
super(message);
this.status = status;
}
}
const e = new HTTPError('Fail', 404);
console.log(JSON.stringify(e)); // {"status":404}
However, if you add a toJSON()
method to your HTTPError
class, you can configure how JavaScript serializes instances of HTTPError
.
class HTTPError extends Error {
constructor(message, status) {
super(message);
this.status = status;
}
toJSON() {
return { message: this.message, status: this.status };
}
}
const e = new HTTPError('Fail', 404);
console.log(JSON.stringify(e)); // {"message":"Fail","status":404}
#javascript #programming #developer