155

My application has a large array of objects, which I stringify and save them to the disk. Unfortunately, when the objects in the array are manipulated, and sometimes replaced, the properties on the objects are listed in different orders (their creation order?). When I do JSON.stringify() on the array and save it, a diff shows the properties getting listed in different orders, which is annoying when trying to merge the data further with diff and merging tools.

Ideally I would like to sort the properties of the objects in alphabetical order prior to performing the stringify, or as part of the stringify operation. There is code for manipulating the array objects in many places, and altering these to always create properties in an explicit order would be difficult.

Suggestions would be most welcome!

A condensed example:

obj = {}; obj.name="X"; obj.os="linux";
JSON.stringify(obj);
obj = {}; obj.os="linux"; obj.name="X";
JSON.stringify(obj);

The output of these two stringify calls are different, and showing up in a diff of my data, but my application doesn't care about the ordering of properties. The objects are constructed in many ways and places.

14
  • Please give an example of the object you're trying to stringify (either JSON output or JS object literal)
    – Bojangles
    Apr 23, 2013 at 10:59
  • 4
    Object keys in objects are not guaranteed to have a fixed order. This is by design.
    – Passerby
    Apr 23, 2013 at 11:07
  • 1
  • 1
    @rab, where did you find that out? Note: It could work (and probably does most of the time), but I meant that it isn't guaranteed to.
    – Dogbert
    Apr 23, 2013 at 12:23
  • 1
    OP here. There was no dependency on property order here, just a question on how to avoid diffs in the serialized data. This was eventually solved by stashing the properties in arrays and sorting them prior to serialization, much like in the accepted answer below.
    – Innovine
    Feb 13, 2018 at 12:28

26 Answers 26

125

The simpler, modern and currently browser supported approach is simply this:

JSON.stringify(sortMyObj, Object.keys(sortMyObj).sort());

However, this method does remove any nested objects that aren't referenced and does not apply to objects within arrays. You will want to flatten the sorting object as well if you want something like this output:

{"a":{"h":4,"z":3},"b":2,"c":1}

You can do that with this:

var flattenObject = function(ob) {
    var toReturn = {};
    
    for (var i in ob) {
        if (!ob.hasOwnProperty(i)) continue;
        
        if ((typeof ob[i]) == 'object') {
            var flatObject = flattenObject(ob[i]);
            for (var x in flatObject) {
                if (!flatObject.hasOwnProperty(x)) continue;
                
                toReturn[i + '.' + x] = flatObject[x];
            }
        } else {
            toReturn[i] = ob[i];
        }
    }
    return toReturn;
};
var myFlattenedObj = flattenObject(sortMyObj);
JSON.stringify(myFlattenedObj, Object.keys(myFlattenedObj).sort());

To do it programmatically with something you can tweak yourself, you need to push the object property names into an array, then sort the array alphabetically and iterate through that array (which will be in the right order) and select each value from the object in that order. "hasOwnProperty" is checked also so you definitely have only the object's own properties. Here's an example:

var obj = {"a":1,"b":2,"c":3};

function iterateObjectAlphabetically(obj, callback) {
    var arr = [],
        i;
    
    for (i in obj) {
        if (obj.hasOwnProperty(i)) {
            arr.push(i);
        }
    }

    arr.sort();
    
    for (i = 0; i < arr.length; i++) {
        var key = obj[arr[i]];
        //console.log( obj[arr[i]] ); //here is the sorted value
        //do what you want with the object property
        if (callback) {
            // callback returns arguments for value, key and original object
            callback(obj[arr[i]], arr[i], obj);
        }
    }
}

iterateObjectAlphabetically(obj, function(val, key, obj) {
    //do something here
});

Again, this should guarantee that you iterate through in alphabetical order.

Finally, taking it further for the simplest way, this library will recursively allow you to sort any JSON you pass into it: https://www.npmjs.com/package/json-stable-stringify

var stringify = require('json-stable-stringify');
var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 };
console.log(stringify(obj));

Output

{"a":3,"b":[{"x":4,"y":5,"z":6},7],"c":8}
17
  • 12
    This is very much what I was trying to avoid :) But thanks, seems like the correct, if heavy, solution.
    – Innovine
    Apr 23, 2013 at 11:31
  • 1
    There's a bug in this code. You can't reference obj[i] in the for loop because i is an integer, and the property names are not necessarily (hence this question). It should be obj[arr[i]]. Jun 19, 2013 at 21:40
  • 1
    Callbacks aren't exclusive to asynchronous behaviour.
    – marksyzm
    Apr 23, 2015 at 19:26
  • 2
    @Johann By using a callback here, he turns iterateObjectAlphabetically into a reusable function. Without the callback the 'payload code' would have to be inside the function itself. I think it's a very elegant solution and one that is used in many libraries and JS core itself. E.g. Array.forEach. Sep 16, 2015 at 8:44
  • 2
    Ah, I must put that bit of information in the very next sentence in the answer! Oh wait...
    – marksyzm
    Jul 30, 2020 at 18:23
60

I don't understand why the complexity of the current best answers is needed, to get all the keys recursively. Unless perfect performance is needed, it seems to me that we can just call JSON.stringify() twice, the first time to get all the keys, and the second time, to really do the job. That way, all the recursion complexity is handled by stringify, and we know that it knows its stuff, and how to handle each object type:

function JSONstringifyOrder(obj, space)
{
    const allKeys = new Set();
    JSON.stringify(obj, (key, value) => (allKeys.add(key), value));
    return JSON.stringify(obj, Array.from(allKeys).sort(), space);
}

Or if you want to support older browsers:

function JSONstringifyOrder(obj, space)
{
    var allKeys = [];
    var seen = {};
    JSON.stringify(obj, function (key, value) {
        if (!(key in seen)) {
            allKeys.push(key);
            seen[key] = null;
        }
        return value;
    });
    allKeys.sort();
    return JSON.stringify(obj, allKeys, space);
}
8
  • thats interesting, but you've actually "cheated" using stringify to map all keys to an array. That array can be easier, better and safer obtained via Object.keys Dec 13, 2018 at 16:57
  • 11
    No, the point is that Object.keys() is not recursive, so if you have an object like {a: "A", b: {c: "C"} } and you call Object.keys on it, you will only get keys a and b, but not c. JSON.stringify knows everything about recursion on every object type handled by the JSON serialization process, be it an object-like or an array (and it already implements the logic to recognize both), so it should handle everything correctly for us.
    – Jor
    Dec 13, 2018 at 21:06
  • 1
    Love this solution, very elegant and fail safe it seems.
    – Markus
    Mar 26, 2019 at 23:04
  • @Jor thanks, that works for me. Others snippets I tried failed one way or another.
    – nevf
    Oct 29, 2020 at 23:40
  • 3
    clever! re perf: I believe this is O(N^2), N=number keys in object, as the sorted keys are checked linearly for every key in the object. So perf will start to be noticeable issue around N > 100K on GHz machines.and perhaps debilitating for N > 1Million. ref: tc39.es/ecma262/#sec-json.stringify Nov 21, 2020 at 0:17
44

I think that if you are in control of the JSON generation (and it sounds like you are), then for your purposes this might be a good solution: json-stable-stringify

From the project website:

deterministic JSON.stringify() with custom sorting to get deterministic hashes from stringified results

If the JSON produced is deterministic you should be able to easily diff/merge it.

5
  • 2
    Note that that repo is in bad shape: hasn't been updated in 3 years and has unresolved issues and pull requests. I think it is better to look to some of the newer answers.
    – Tom
    Feb 2, 2019 at 15:29
  • 7
    @Tom Also note that that repo has 5 million weekly (!) downloads. In other words, it's actively being used. Having 'unresolved' open issues and/or pull requests does not mean much. Just that the author(s) don't care about those issues or have no time etc. Not every lib needs to be updated every couple of months. In fact, imho, the best libs get updates very infrequently. When something is done, it's done. I'm not saying this project has no real issues, but if so, please point those out. I have no involvement with this lib BTW. Feb 18, 2019 at 11:16
  • ES6 I guess broke it being able to sort objects (non-arrays), as specified. I need this for user editing. Even if order does not matter to the computer. It does to the users editing it. It was worth trying. Jul 26, 2019 at 20:37
  • 1
    On top of what @Tom says, I'll also point out that this project has no runtime dependencies. Meaning that if there are no security / maintenance issues in this repo, then it's probably pretty stable and safe to use. Also, I just tested it with ES6 and it seems to work fine (in Firefox at least).
    – Phil
    Feb 26, 2020 at 12:03
  • The latest version of the library was released 2 days ago, 6 years after the last change.
    – M. Justin
    Nov 9, 2022 at 22:15
33

You can pass a sorted array of the property names as the second argument of JSON.stringify():

JSON.stringify(obj, Object.keys(obj).sort())
4
  • 2
    Is there any sort of documented guarantee on this behavior?
    – rich remer
    Jan 21, 2017 at 3:23
  • 4
    @richremer Yes, in the ECMAScript standard, the second parameter of JSON.stringify() is called replacer and can be an array. It is used to build a PropertyList which is then used in SerializeJSONObject() to append the properties in that order. This is documented since ECMAScript 5. Jan 21, 2017 at 4:35
  • 22
    Note that if obj has nested objects in it, the nested keys must be present in the second argument as well; otherwise, they will be dropped! Counter-example: > JSON.stringify({a: {c: 1, b: 2}}, ['a']) '{"a":{}}' One (hacky) way to build the list of all relevant keys is to use JSON.stringify to traverse the object: function orderedStringify(obj) { const allKeys = []; JSON.stringify(obj, (k, v) => { allKeys.push(k); return v; }); return JSON.stringify(obj, allKeys.sort()); } Example: > orderedStringify({a: {c: 1, b: 2}}) '{"a":{"b":2,"c":1}}'
    – Saif Hakim
    Apr 5, 2017 at 17:24
  • 4
    Object.keys() is not recursive. This will not work for any object containing nested arrays or objects.
    – Jor
    Feb 29, 2020 at 13:57
31

JSON.stringify() replacer function for having object keys sorted in output (supports deeply nested objects).

const replacer = (key, value) =>
value instanceof Object && !(value instanceof Array) ? 
    Object.keys(value)
    .sort()
    .reduce((sorted, key) => {
        sorted[key] = value[key];
        return sorted 
    }, {}) :
    value;

// Usage
// JSON.stringify({c: 1, a: { d: 0, c: 1, e: {a: 0, 1: 4}}}, replacer);

GitHub Gist page here.

6
18

Update 2018-7-24:

This version sorts nested objects and supports array as well:

function sortObjByKey(value) {
  return (typeof value === 'object') ?
    (Array.isArray(value) ?
      value.map(sortObjByKey) :
      Object.keys(value).sort().reduce(
        (o, key) => {
          const v = value[key];
          o[key] = sortObjByKey(v);
          return o;
        }, {})
    ) :
    value;
}


function orderedJsonStringify(obj) {
  return JSON.stringify(sortObjByKey(obj));
}

Test case:

  describe('orderedJsonStringify', () => {
    it('make properties in order', () => {
      const obj = {
        name: 'foo',
        arr: [
          { x: 1, y: 2 },
          { y: 4, x: 3 },
        ],
        value: { y: 2, x: 1, },
      };
      expect(orderedJsonStringify(obj))
        .to.equal('{"arr":[{"x":1,"y":2},{"x":3,"y":4}],"name":"foo","value":{"x":1,"y":2}}');
    });

    it('support array', () => {
      const obj = [
        { x: 1, y: 2 },
        { y: 4, x: 3 },
      ];
      expect(orderedJsonStringify(obj))
        .to.equal('[{"x":1,"y":2},{"x":3,"y":4}]');
    });

  });

Deprecated answer:

A concise version in ES2016. Credit to @codename , from https://stackoverflow.com/a/29622653/94148

function orderedJsonStringify(o) {
  return JSON.stringify(Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {}));
}
5
  • Syntax not quite right. Should be - function orderedJsonStringify(o) { return JSON.stringify(Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {})); }
    – Ben
    May 27, 2016 at 9:58
  • This, for now, has fixed my issue with C# DataContractJsonSerializer and "__type" not being listed first in the json string. Thanks. Sep 2, 2016 at 21:18
  • 3
    Note that this, like Christian's answer, misbehaves with nested objects. Nov 20, 2017 at 21:10
  • sortObjPropertiesByKey is not defined. Did you mean to use sortObjByKey?
    – Paul Lynch
    Sep 5, 2018 at 21:14
  • 2
    It does not seem that this sortObjByKey() checks for circular references, so be careful, it may hang in an infinite loop depending on input data. Example: var objA = {}; var objB = {objA: objA}; objA.objB = objB; -> sortObjByKey(objA); -> VM59:6 Uncaught RangeError: Maximum call stack size exceeded
    – Klesun
    Dec 8, 2019 at 21:50
4

This is same as Satpal Singh's answer

function stringifyJSON(obj){
    keys = [];
    if(obj){
        for(var key in obj){
            keys.push(key);
        }
    }
    keys.sort();
    var tObj = {};
    var key;
    for(var index in keys){
        key = keys[index];
        tObj[ key ] = obj[ key ];
    }
    return JSON.stringify(tObj);
}

obj1 = {}; obj1.os="linux"; obj1.name="X";
stringifyJSON(obj1); //returns "{"name":"X","os":"linux"}"

obj2 = {}; obj2.name="X"; obj2.os="linux";
stringifyJSON(obj2); //returns "{"name":"X","os":"linux"}"
4

A recursive and simplified answer:

function sortObject(obj) {
    if(typeof obj !== 'object')
        return obj
    var temp = {};
    var keys = [];
    for(var key in obj)
        keys.push(key);
    keys.sort();
    for(var index in keys)
        temp[keys[index]] = sortObject(obj[keys[index]]);       
    return temp;
}

var str = JSON.stringify(sortObject(obj), undefined, 4);
7
  • reorder should be renamed to sortObject and this doesn't handle arrays
    – jgawrych
    Apr 2, 2015 at 0:42
  • Thanks for noticing that, and OP's issue was resorting objects, not arrays. Apr 2, 2015 at 13:23
  • @JonathanGawrych Why would you sort arrays anyway, they are supposed to have an order. An array [1,2,3] is not the same as an array [2,3,1], but an object has no property order. The problem is that order suddenly matters after stringification - the strings for 100% equivalent objects can be different. Unfortunately the effort to get a deterministic stringify seems considerable, example package: github.com/substack/json-stable-stringify/blob/master/index.js
    – Mörre
    Nov 25, 2016 at 14:46
  • 1
    @Mörre - I guess I wasn't specific enough. By "doesn't handle arrays," I meant arrays are broken, not left unsorted. The problem is because typeof arr === "object" it would transform arrays into objects. For example var obj = {foo: ["bar", "baz"]} would be stringified into { "foo": { "0": "bar", "1": "baz"} }
    – jgawrych
    Nov 29, 2016 at 19:12
  • to fix the issue found by @JonathanGawrych: if(obj.constructor.prototype !== Object.prototype)
    – ricka
    Nov 9, 2017 at 6:29
4

You can sort object by property name in EcmaScript 2015

function sortObjectByPropertyName(obj) {
    return Object.keys(obj).sort().reduce((c, d) => (c[d] = obj[d], c), {});
}
1
  • Maybe a better name would be sortObjectPropertiesByName() or more simple sortPropertiesByName().
    – Jan
    Nov 13, 2018 at 13:03
3

You can add a custom toJSON function to your object which you can use to customise the output. Inside the function, adding current properties to a new object in a specific order should preserve that order when stringified.

See here:

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify

There's no in-built method for controlling ordering because JSON data is meant to be accessed by keys.

Here's a jsfiddle with a small example:

http://jsfiddle.net/Eq2Yw/

Try commenting out the toJSON function - the order of the properties is reversed. Please be aware that this may be browser-specific, i.e. ordering is not officially supported in the specification. It works in the current version of Firefox, but if you want a 100% robust solution, you may have to write your own stringifier function.

Edit:

Also see this SO question regarding stringify's non-deterministic output, especially Daff's details about browser differences:

How to deterministically verify that a JSON object hasn't been modified?

2
  • The properties of each object are known (and mostly strings) so hardcoding the properties in my own toJSON stringifier might be much quicker than sorting...!
    – Innovine
    Apr 23, 2013 at 11:37
  • The 'orderedJsonStringify' below almost worked. But this looks to be a better solution for me. When i need to get '__type' of the C# DataContractJsonSerializer to be the first item in the json string. var json = JSON.stringify(myjsonobj, ['__type', 'id', 'text', 'somesubobj' etc.....]); a little pain to have list all the keys. Sep 9, 2016 at 19:12
3

I took the answer from @Jason Parham and made some improvements

function sortObject(obj, arraySorter) {
    if(typeof obj !== 'object')
        return obj
    if (Array.isArray(obj)) {
        if (arraySorter) {
            obj.sort(arraySorter);
        }
        for (var i = 0; i < obj.length; i++) {
            obj[i] = sortObject(obj[i], arraySorter);
        }
        return obj;
    }
    var temp = {};
    var keys = [];
    for(var key in obj)
        keys.push(key);
    keys.sort();
    for(var index in keys)
        temp[keys[index]] = sortObject(obj[keys[index]], arraySorter);       
    return temp;
}

This fixes the issue of arrays being converted to objects, and it also allows you to define how to sort arrays.

Example:

var data = { content: [{id: 3}, {id: 1}, {id: 2}] };
sortObject(data, (i1, i2) => i1.id - i2.id)

output:

{content:[{id:1},{id:2},{id:3}]}
3

I just rewrote one of mentioned examples to use it in stringify

const stringifySort = (key, value) => {
    if (!value || typeof value !== 'object' || Array.isArray(value)) return value;
    return Object.keys(value).sort().reduce((obj, key) => (obj[key]=value[key], obj), {});
};

JSON.stringify({name:"X", os:"linux"}, stringifySort);
2

The accepted answer does not work for me for nested objects for some reason. This led me to code up my own. As it's late 2019 when I write this, there are a few more options available within the language.

Update: I believe David Furlong's answer is a preferable approach to my earlier attempt, and I have riffed off that. Mine relies on support for Object.entries(...), so no Internet Explorer support.

function normalize(sortingFunction) {
  return function(key, value) {
    if (typeof value === 'object' && !Array.isArray(value)) {
      return Object
        .entries(value)
        .sort(sortingFunction || undefined)
        .reduce((acc, entry) => {
          acc[entry[0]] = entry[1];
          return acc;
        }, {});
    }
    return value;
  }
}

JSON.stringify(obj, normalize(), 2);

--

KEEPING THIS OLDER VERSION FOR HISTORICAL REFERENCE

I found that a simple, flat array of all keys in the object will work. In almost all browsers (not Edge or Internet explorer, predictably) and Node 12+ there is a fairly short solution now that Array.prototype.flatMap(...) is available. (The lodash equivalent would work too.) I have only tested in Safari, Chrome, and Firefox, but I see no reason why it wouldn't work anywhere else that supports flatMap and standard JSON.stringify(...).

function flattenEntries([key, value]) {
  return (typeof value !== 'object')
    ? [ [ key, value ] ]
    : [ [ key, value ], ...Object.entries(value).flatMap(flattenEntries) ];
}

function sortedStringify(obj, sorter, indent = 2) {
  const allEntries = Object.entries(obj).flatMap(flattenEntries);
  const sorted = allEntries.sort(sorter || undefined).map(entry => entry[0]);
  return JSON.stringify(obj, sorted, indent);
}

With this, you can stringify with no 3rd-party dependencies and even pass in your own sort algorithm that sorts on the key-value entry pairs, so you can sort by key, payload, or a combination of the two. Works for nested objects, arrays, and any mixture of plain old data types.

const obj = {
  "c": {
    "z": 4,
    "x": 3,
    "y": [
      2048,
      1999,
      {
        "x": false,
        "g": "help",
        "f": 5
      }
    ]
  },
  "a": 2,
  "b": 1
};

console.log(sortedStringify(obj, null, 2));

Prints:

{
  "a": 2,
  "b": 1,
  "c": {
    "x": 3,
    "y": [
      2048,
      1999,
      {
        "f": 5,
        "g": "help",
        "x": false
      }
    ],
    "z": 4
  }
}

If you must have compatibility with older JavaScript engines, you could use these slightly more verbose versions that emulate flatMap behavior. Client must support at least ES5, so no Internet Explorer 8 or below.

These will return the same result as above.

function flattenEntries([key, value]) {
  if (typeof value !== 'object') {
    return [ [ key, value ] ];
  }
  const nestedEntries = Object
    .entries(value)
    .map(flattenEntries)
    .reduce((acc, arr) => acc.concat(arr), []);
  nestedEntries.unshift([ key, value ]);
  return nestedEntries;
}

function sortedStringify(obj, sorter, indent = 2) {
  const sortedKeys = Object
    .entries(obj)
    .map(flattenEntries)
    .reduce((acc, arr) => acc.concat(arr), [])
    .sort(sorter || undefined)
    .map(entry => entry[0]);
  return JSON.stringify(obj, sortedKeys, indent);
}
2

An additional solution that works for nested objects as well:

const myFunc = (key) =>
  JSON.stringify(key, (_, v) =>
    v.constructor === Object ? Object.entries(v).sort() : v
  );
  
const jsonFunc = JSON.stringify;
  
const obj1 = {
  key1: "value1",
  key2: {
    key3: "value2",
    key4: "value3",
  },
};
  
const obj2 = {
  key2: {
    key4: "value3",
    key3: "value2",
  },
  key1: "value1",
};

console.log(`JSON: ${jsonFunc(obj1) === jsonFunc(obj2)}`);
console.log(`My: ${myFunc(obj1) === myFunc(obj2)}`);

1

Works with lodash, nested objects, any value of object attribute:

function sort(myObj) {
  var sortedObj = {};
  Object.keys(myObj).sort().forEach(key => {
    sortedObj[key] = _.isPlainObject(myObj[key]) ? sort(myObj[key]) : myObj[key]
  })
  return sortedObj;
}
JSON.stringify(sort(yourObj), null, 2)

It relies on Chrome's and Node's behaviour that the first key assigned to an object is outputted first by JSON.stringify.

2
  • 2
    Thanks, but I had this problem 4 years ago, I'm happy to say I've moved on a bit since then :)
    – Innovine
    Aug 8, 2017 at 19:20
  • 1
    :) Good to hear it. Though I had this problem yesterday and didn't find the answer I was looking for under your (old but still relevant) question :)
    – AJP
    Aug 9, 2017 at 13:00
1

After all, it needs an Array that caches all keys in the nested object (otherwise it will omit the uncached keys.) The oldest answer is just plain wrong, because second argument doesn't care about dot-notation. So, the answer (using Set) becomes.

function stableStringify (obj) {
  const keys = new Set()
  const getAndSortKeys = (a) => {
    if (a) {
      if (typeof a === 'object' && a.toString() === '[object Object]') {
        Object.keys(a).map((k) => {
          keys.add(k)
          getAndSortKeys(a[k])
        })
      } else if (Array.isArray(a)) {
        a.map((el) => getAndSortKeys(el))
      }
    }
  }
  getAndSortKeys(obj)
  return JSON.stringify(obj, Array.from(keys).sort())
}
0

Try:

function obj(){
  this.name = '';
  this.os = '';
}

a = new obj();
a.name = 'X',
a.os = 'linux';
JSON.stringify(a);
b = new obj();
b.os = 'linux';
b.name = 'X',
JSON.stringify(b);
1
  • Thanks, but apparently the ordering is undefined and only happens to work. Interesting approach though!
    – Innovine
    Apr 23, 2013 at 11:28
0

I made a function to sort object, and with callback .. which actually create a new object

function sortObj( obj , callback ) {

    var r = [] ;

    for ( var i in obj ){
        if ( obj.hasOwnProperty( i ) ) {
             r.push( { key: i , value : obj[i] } );
        }
    }

    return r.sort( callback ).reduce( function( obj , n ){
        obj[ n.key ] = n.value ;
        return obj;
    },{});
}

and call it with object .

var obj = {
    name : "anu",
    os : "windows",
    value : 'msio',
};

var result = sortObj( obj , function( a, b ){
    return a.key < b.key  ;    
});

JSON.stringify( result )

which prints {"value":"msio","os":"windows","name":"anu"} , and for sorting with value .

var result = sortObj( obj , function( a, b ){
    return a.value < b.value  ;    
});

JSON.stringify( result )

which prints {"os":"windows","value":"msio","name":"anu"}

1
  • 1
    Works well, but unfortunately it's not recursive.
    – jgawrych
    Apr 2, 2015 at 0:46
0

If objects in the list does not have same properties, generate a combined master object before stringify:

let arr=[ <object1>, <object2>, ... ]
let o = {}
for ( let i = 0; i < arr.length; i++ ) {
  Object.assign( o, arr[i] );
}
JSON.stringify( arr, Object.keys( o ).sort() );

0
function FlatternInSort( obj ) {
    if( typeof obj === 'object' )
    {
        if( obj.constructor === Object )
        {       //here use underscore.js
            let PaireStr = _( obj ).chain().pairs().sortBy( p => p[0] ).map( p => p.map( FlatternInSort ).join( ':' )).value().join( ',' );
            return '{' + PaireStr + '}';
        }
        return '[' + obj.map( FlatternInSort ).join( ',' ) + ']';
    }
    return JSON.stringify( obj );
}

// example as below. in each layer, for objects like {}, flattened in key sort. for arrays, numbers or strings, flattened like/with JSON.stringify.

FlatternInSort( { c:9, b: { y: 4, z: 2, e: 9 }, F:4, a:[{j:8, h:3},{a:3,b:7}] } )

"{"F":4,"a":[{"h":3,"j":8},{"a":3,"b":7}],"b":{"e":9,"y":4,"z":2},"c":9}"

2
  • Please explain why using an external lib, and as @DeKaNszn said, add some explanations and an introduction. It would be appreciated.
    – Benj
    Aug 25, 2017 at 14:32
  • this funtion is copied from my project. in which i use underscore.js.
    – saintthor
    Aug 26, 2017 at 15:25
0

Extending AJP's answer, to handle arrays:

function sort(myObj) {
    var sortedObj = {};
    Object.keys(myObj).sort().forEach(key => {
        sortedObj[key] = _.isPlainObject(myObj[key]) ? sort(myObj[key]) : _.isArray(myObj[key])? myObj[key].map(sort) : myObj[key]
    })
    return sortedObj;
}
0

Surprised nobody has mentioned lodash's isEqual function.

Performs a deep comparison between two values to determine if they are equivalent.

Note: This method supports comparing arrays, array buffers, booleans, date objects, error objects, maps, numbers, Object objects, regexes, sets, strings, symbols, and typed arrays. Object objects are compared by their own, not inherited, enumerable properties. Functions and DOM nodes are compared by strict equality, i.e. ===.

https://lodash.com/docs/4.17.11#isEqual

With the original problem - keys being inconsistently ordered - it's a great solution - and of course it will just stop if it finds a conflict instead of blindly serializing the whole object.

To avoid importing the whole library you do this:

import { isEqual } from "lodash-es";

Bonus example: You can also use this with RxJS with this custom operator

export const distinctUntilEqualChanged = <T>(): MonoTypeOperatorFunction<T> => 
                                                pipe(distinctUntilChanged(isEqual));
0

Here is a clone approach...clone the object before converting to json:

function sort(o: any): any {
    if (null === o) return o;
    if (undefined === o) return o;
    if (typeof o !== "object") return o;
    if (Array.isArray(o)) {
        return o.map((item) => sort(item));
    }
    const keys = Object.keys(o).sort();
    const result = <any>{};
    keys.forEach((k) => (result[k] = sort(o[k])));
    return result;
}

If is very new but seems to work on package.json files fine.

0

Don't be confused with the object monitoring of Chrome debugger. It shows sorted keys in object, even though actually it is not sorted. You have to sort the object before you stringify it.

1
  • Thanks for pointing this out. The above was for a nodejs application, but if Chrome's debugger is sorting things by itself then that's certainly useful information for someone, someday. Maybe they will comment here when they see this :)
    – Innovine
    Jan 3, 2021 at 15:40
0

Before I found libs like fast-json-stable-stringify (haven't tested it in production myself), I was doing it this way:

import { flatten } from "flat";
import { set } from 'lodash/fp';

const sortJson = (jsonString) => {
  const object = JSON.parse(jsonString);
  const flatObject = flatten(object);
  const propsSorted = Object.entries(flatObject).map(([key, value]) => ({ key, value })).sort((a, b) => a.key.localeCompare(b.key));
  const objectSorted = propsSorted.reduce((object, { key, value }) => set(key, value, object), {});
  return JSON.stringify(objectSorted);
};


const originalJson = JSON.stringify({ c: { z: 3, x: 1, y: 2 }, a: true, b: [ 'a', 'b', 'c' ] });
console.log(sortJson(originalJson)); // {"a":true,"b":["a","b","c"],"c":{"x":1,"y":2,"z":3}} 
-4

There is Array.sort method which can be helpful for you. For example:

yourBigArray.sort(function(a,b){
    //custom sorting mechanism
});
4
  • 1
    I don't wish to sort the array though. Actually the array part is not important.. I wish to sort the properties of an object.. from a few quick experiments it looks like properties are listed in the order that they are created. One way might be to create a new object and copy the properties in alphabetical order but I'm hoping there is something easier/quicker..
    – Innovine
    Apr 23, 2013 at 11:07
  • 1
    @Innovine, even that wouldn't work as keys are not guaranteed to be ordered by creation time by the spec.
    – Dogbert
    Apr 23, 2013 at 11:09
  • Then the question becomes, how do I stringify my objects in such a way that the keys are in a fixed order.. it's not impossible for me to do for (key in obj) and store them in a temp array and sort that and manually construct a string.. but I'm desperately hoping there is an easier way
    – Innovine
    Apr 23, 2013 at 11:21
  • No, that is pretty much the way to do it. Welcome to JavaScript.
    – marksyzm
    Apr 23, 2013 at 11:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.