own2json
Stringify objects' own properties.
The Problem
Some objects (read Error
s) don't stringify the way you'd like them to:
const err = 'foo'; console;// Logs {}
The Solution
own2json
exports a single method, which can be used as an object's toJSON()
method. The result is that JSON.stringify()
will contain all of the properties returned by Object.getOwnPropertyNames()
that can be stringified (undefined
, functions, etc. will not be included).
const Own2Json = ;const err = 'foo'; e2toJSON = Own2Json;console;// Value contains error's `message` and `stack`// Only applies to `e2`
This technique can be applied to prototypes as well (although modifying builtins is not recommended):
const Own2Json = ;const err = 'foo'; ErrorprototypetoJSON = Own2Json;console;// Value contains error's `message` and `stack`// Applies to all Error objects