Skip to content

A deterministic version of JSON.stringify that sorts object keys alphabetically.

License

Notifications You must be signed in to change notification settings

ThomasR/JSON.sortify

Repository files navigation

JSON.sortify

npm version Build Status Test Coverage Code Climate

A deterministic version of JSON.stringify that sorts object keys alphabetically.

Inspired by http://stackoverflow.com/questions/8931967/is-there-a-deterministic-equivalent-of-json-stringify

Install as an NPM module

$ npm install json.sortify

Usage

let jsonSortify = require('json.sortify');

or

JSON.sortify = require('json.sortify');

or even

JSON.stringify = require('json.sortify');

JSON.sortify is fully compatible with JSON.stringify, so you can overwrite the native implementation without any problems.

In HTML

Download JSON.sortify.js and save it to your server.

<script src="JSON.sortify.js"></script> <!-- will inject the JSON.sortify() function -->

Or, if you're using bower, type bower install json.sortify.

<script src="bower_components/json.sortify/dist/JSON.sortify.js"></script>

JSON.sortify can be used exactly like JSON.stringify. As mentioned above, you can overwrite JSON.stringify if you want to:

<script src="JSON.sortify.js"></script>
<script>JSON.stringify = JSON.sortify</script>

AMD module

You can also use JSON.sortify as an AMD module:

require(['json.sortify'], function (jsonSortify) {  });

How to use

Use JSON.sortify exactly like JSON.stringify. Refer to MDN:JSON/stringify for details.

Basic

JSON.sortify({a:1,b:2});
{"a":1,"b":2}

Sorting

JSON.sortify({b:1,a:2,c:3,5:4});
{"5":4,"a":2,"b":1,"c":3}

Indentation:

JSON.sortify({b:1,a:2}, null, 2);
{
  "a": 2,
  "b": 1
}

Whitelisting of object keys:

JSON.sortify({b:1,foo:2,a:3}, ['a', 'foo'], 4);
{
    "a": 3,
    "foo": 2
}

Replacer Function:

JSON.sortify({b:1,foo:'woot',a:3}, function (key, value) {
    return typeof value == 'string' ? value + '!!!' : value;
}, '\t');
{
        "a": 3,
        "b": 1,
        "foo": "woot!!!"
}

License: Apache 2.0