npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ea-json

v1.0.0

Published

json stringify and parse typed data restoring appropriate class on Date Buffer and any class implementing a static fromJSON method

Downloads

6

Readme

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 = require("ea-json")

// NOTE: usually you woud just define those methods inside some modules you require
// ----
Buffer.fromJSON = function(json) {
	return new Buffer(json,'base64');
}
Buffer.prototype.toJSON = function() {
	return {
		type: "Buffer",
		data: this.toString('base64')
	}
}

RegExp.fromJSON = ([source,global])=>new RegExp(source||'',(global?"g":""));
RegExp.prototype.toJSON = function() { return ({type:"RegExp", data:[this.source,this.global]}) }

Date.fromJSON = function(json) {
    return new Date(json);
}

Date.prototype.toJSON = function() { 
    return {type: 'Date', data: this.toISOString()}; 
}

// Sample Object
var sample = { 
    user: {
        name: 'earendel',
        email: '[email protected]'
    },
    // 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: new Date(),
    buffer: new Buffer('hello world')
};

//works!
var recreated = json.parse(json.stringify(sample));

console.log(require("util").inspect(recreated,{depth:null}));

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 
exports.require = {};

// 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) => {} 
exports.fromJSON = {};



//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.parse = (json,custom) => {
    return JSON.parse(json, (k,v) => {
        var type = v.type;
        var data = v.data;
		if((type !== undefined) && (data !== undefined)) { 
            var construct = exports.require[type] || global[type] || (/^[a-z_]+[a-z0-9_]*$/i.test(type) && eval(`typeof(${type})=="function" && ${type}`)); 
			if(construct && construct.fromJSON && typeof(construct.fromJSON) == "function" ) {
                return construct.fromJSON(data);
			} else if(exports.fromJSON[type] && typeof(exports.from[type]) == "function") {
				return exports.fromJSON[type](data);
            }
        }; 
        if(custom && typeof(custom)=="function") {
            return custom(k,v)
        } else {
            return v;
        }
    });
};  
var stringify = exports.stringify = (obj) => JSON.stringify(obj);


exports.sample = { 
    user: {
        name: 'earendel',
        email: '[email protected]'
    },
    // 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: new Date(),
    buffer: new Buffer('hello world')
};