Skip to content
This repository has been archived by the owner on Mar 15, 2020. It is now read-only.

cjihrig/own2json

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

own2json

Current Version Build Status via Travis CI Dependencies belly-button-style

Stringify objects' own properties.

The Problem

Some objects (read Errors) don't stringify the way you'd like them to:

const err = new Error('foo');

console.log(JSON.stringify(err));
// 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 = require('own2json');
const err = new Error('foo');

e2.toJSON = Own2Json;
console.log(JSON.stringify(err));
// 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 = require('own2json');
const err = new Error('foo');

Error.prototype.toJSON = Own2Json;
console.log(JSON.stringify(err));
// Value contains error's `message` and `stack`
// Applies to all Error objects