super-json
Library that provides JSON serialization of javascript objects not supported natively by JSON such as Dates, RegExps, Functions or any other user-defined class instance.
Installation
npm install super-json
Usage
// Nodejs> var superJson = ; // Browser> var superJson = windowsuperJson; > var myJson = superJson; // or just> var myJson = superJson; // The above options are defaults. > myJson; '{"birth":"#!Date[0]","someRegex":"#!RegExp[\\"abc\\",\\"gi\\"]"}' > myJson birth: Wed Dec 31 1969 21:00:00 GMT- someRegex: /abc/gi
It is possible to use 'myJson' as a drop-in replacement for the global JSON object, but if the replacer/reviver arguments are used the custom serialization will not work.
Implementation
This is implemented using the replacer/reviver arguments, and serializes custom types to a string that looks like this: {magic}{serializer name}{json array containing constructor arguments}. The magic string is escaped when serializing strings, so user input doesn't need to be validated.
Customize serialization
Just pass an object that looks like this(example from the date serializer):
dateSerializer = { return date; } { return time; } { return obj instanceof Date; } name: 'Date'