Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including super-json with all npm packages installed. Try it out:

var superJson = require("super-json")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

super-json v2.2.0

JSON serializer that handles Dates, RegExps, Functions or any other type you want

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 = require('super-json');

// Browser
> var superJson = window.superJson;

> var myJson = superJson.create({
...  magic: '#!',
...  serializers: [
...    superJson.dateSerializer,
...    superJson.regExpSerializer,
...    superJson.functionSerializer
...  ]
...});

// or just
> var myJson = superJson.create(); // The above options are defaults.

> myJson.stringify({birth: new Date(0), someRegex: /abc/gi}); 
'{"birth":"#!Date[0]","someRegex":"#!RegExp[\\"abc\\",\\"gi\\"]"}'

> myJson.parse(myJson.stringify({birth: new Date(0), someRegex: /abc/gi})) 
{ birth: Wed Dec 31 1969 21:00:00 GMT-0300 (BRT),
  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 = {
  serialize: function(date) {
    return [date.getTime()];
  },
  deserialize: function(time) {
    return new Date(time);
  },
  isInstance: function(obj) {
    return obj instanceof Date;
  },
  name: 'Date'
}

Metadata

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free