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

to-json

v0.5.0-prerelease

Published

Provides a consistent mechanism for mapping complex javascript data to json. This mechanism allows for complex filtering, data conversion, and two-way mapping between the input and output data.

Downloads

8

Readme

to-json

to-json provides a consistent mechanism for mapping complex javascript data to json. This mechanism allows for complex filtering, data conversion, and two-way mapping between the input and output data.

Build Status Coverage Status

Installation

Node

npm install to-json

Web

bower install to-json

Usage

node

var toJson = require('to-json');

console.log(toJson([1,2,3]));

web (global)

<html>
    <head>
        <script type="text/javascript" src="to-json.web.min.js"></script>
    </head>
    <body>
        <script>
            console.log(toJson([1,2,3]));
        </script>
    </body>
</html>

web (amd)

require.config({
  paths: {
      "to-json": "to-json.web.min.js"
  }
});
require(['to-json'], function (toJson) {
    console.log(toJson([1,2,3]));
});

Simple Usage

Convert data to json using default mappers and direct copies. When converting data, the toJson and toJSON methods are used wherever they are found.

var json = toJson([1,2,3]);

IO Mapping Usage

Convert data to json whilst simulataniously producing a mapping object.

Path Map

Produce a 1:1 map of json path to data path strings.

var context = new toJson.WithPathMap([1,2,3]);
var json = context.apply();
var pathMap = context.pathMap;

Path Tree

Produce a mapping tree of json key/index to data key/index.

var context = new toJson.WithPathTree([1,2,3]);
var json = context.apply();
var pathTree = context.pathTree;

Data Map

Produce a 1:1 map of json paths to input data.

var context = new toJson.WithDataMap([1,2,3]);
var json = context.apply();
var dataMap = context.dataMap;

Data Tree

Produce a mapping tree of json key/index to data key/index of input data.

var context = new toJson.WithDataTree([1,2,3]);
var json = context.apply();
var dataTree = context.dataTree;

Advanced Usage

Customise the mapping process before converting data to json.

var context = new toJson([1,2,3]);

// customise the context

var json = context.apply();

Customisation

It is often desirable to adjust the mapping process at various levels within the process. Mapping overrides can be applied at the following levels

Only to the current context

context._toJson = ...

or

context.adjustContext({
  _toJson: ...
});

Only to the current context and immediate child contexts

context.adjustChildContexts({
  _toJson: ...
});

Only to the current nodes decedents

context.adjustChildContexts({
  _toJson: ...
}, true);

To the current node and all its decedents

context.adjustContext({
  _toJson: ...
}, true);

Available customisations

The following customisations can be applied at any of the levels mentioned above.

Custom naming

By default, json object keys are identical to the keys in the source data. Change this method to customise the key name used in the json output.

// Custom usage requires access to the context
var context = new toJson({a: 1, b: 2});

// Customise only the current node to uppercase all keys
// Note: names are determined by the parent item
context._getJsonKey = function (dataKey) {
    return dataKey.toUpperCase();
}

var json = context.apply();
// { A: 1, B: 2 }

Filtering

Exclude unwanted input data from being returned in the json output. to-json supports exclusions at each of the following stages:

  • immediately (_exclude) - Has access to the context, input data, and mapping keys
  • after data conversion (_excludeData) - Has access to the context, converted input data, and mapping keys
  • after conversion to json (_excludeJson) - Has access to the context, converted input data, mapping keys and json output
// Custom usage requires access to the context
var context = new toJson(['a','b','c','d']);

// Customise all immediate children to exclude odd indexes
context.adjustChildContexts({
  _exclude: function () {
    return typeof (this.dataKey == 'number') && (this.dataKey % 2 == 1);
  }
});

var json = context.apply();
// ['a','c']

Data conversion

Convert incoming data before it is converted to json.

// Custom usage requires access to the context
var context = new toJson([0,1,2,3,4]);

// Customise all immediate children to double incoming values
context.adjustChildContexts({
  _convertData: function () {
    this.data = this.data*2;
  }
});

var json = context.apply();
// [0,2,4,6,8]

Json conversion

Convert outgoing json data.

// Custom usage requires access to the context
var context = new toJson([0,1,2,3,4]);

// Customise all immediate children to double outgoing values
context.adjustChildContexts({
  _toJson: function () {
    // call super function to do the original conversion
    this._callSuper('_toJson');

    // double each output value
    this.json = this.json*2;
  }
});

var json = context.apply();
// [0,2,4,6,8]

Input data enumeration

Customise the way incoming data is enumerated. Enumeration can be customised for:

  • Arrays (_getEnumeratorArray)
  • Objects (_getEnumeratorObject)
  • Values (_getEnumeratorValue)
  • ..or everything at once (_getEnumerator)
// Custom usage requires access to the context
var context = new toJson([0,1,2,3,4]);

// Return a callback for iterating over arrays which skips the first element
context._getEnumerator = function () {
  var _this = this;
  return function (cb) {
    var i,length = _this.data.length;
    // Set the output json
    _this.json = [];
    for (i = 1; i < length; ++i) {
      // cb(value, dataKey, jsonKey)
      cb(_this.data[i], i, _this.json.length);
    }
    // Return the resulting json
    return _this.json;
  };
}

var json = context.apply();
// [0,1,2,3]

Classes / Prototypes

When enumerating input data, to-json checks for the presence of toJson(context) and toJSON() functions. If either is found, the result of those functions is used to provide data to json mappings.

By overriding these methods, classes can customise their data-to-json mapping process in a standardised way

// Example class
function MyObject() {
  this.a = 1;
  this.b = 2;
}
MyObject.prototype.c = 3;

MyObject.prototype.toJSON = function () {
  return toJson(this);
}
MyObject.prototype.toJson = function (context) {
  // customise the context
  ...

  // apply the context
  return context.apply(true);
}