ea-json
If you JSON.stringify instances of Buffer or Date, it may work. Yet parsing the stringified data doesn't result in recreating the proper type. This module's parse method will look for a static fromJSON method whenever a json property contains a "type" and "data" tree, where type is the class name and data the data passed to the fromJSON method.
Install
npm install ea-json --save
Example
var json = // NOTE: usually you woud just define those methods inside some modules you require// ----Buffer { return json'base64';}Bufferprototype { return type: "Buffer" data: this } RegExpsource||''global?"g":"";RegExpprototype { return type:"RegExp" data:thissourcethisglobal } Date { return json;} Dateprototype { return type: 'Date' data: this; } // Sample Objectvar sample = user: name: 'earendel' email: 'kasia99@gmx.de' // have added this to show you can (by some chance or at will) still // have a node with a type and data key node: type: 'SpaceShuttle' data: '\\_----@>' date: buffer: 'hello world'; //works!var recreated = json; console;
Appendix
//to be implemented
//*
interface JSON.Serializable
{
({type: string, data: string}) toJSON(): [Function],
({instance of type}) static fromJSON(data): [Function]
}
/* */
//toJSON() and fromJSON() are functions to be implement by contract of the interface
// a) require[type] = class constructor implementing JSON.serializable exportsrequire = {}; // b) like above but in global[type] // c) var T = eval(type); (T && typeof(T) == "function" && T.fromJSON) ..use required class constructors in local vars // d) alternatively just a function in: fromJSON[type] = (data) => {} exportsfromJSON = {}; //As initially intended JSON.parseTyped investigates class methods looking for a static .fromJSON() as a pendant to nativly lookup for customized prototype.toJSON() method. //if it finds a .fromJSON() for the v.type it invokes with v.data as argument (if there is no {type} OR {data} or proper factory found, default JSON.parse is used on the entire tree v) var parse = exports { return JSON;}; var stringify = exports JSON; exportssample = user: name: 'earendel' email: 'kasia99@gmx.de' // have added this to show you can (by some chance or at will) still // have a node with a type and data key node: type: 'SpaceShuttle' data: '\\_----@>' date: buffer: 'hello world';