sort object properties and JSON.stringify

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 = {};"X"; obj.os="linux";
obj = {}; obj.os="linux";"X";

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.

18 thoughts on “sort object properties and JSON.stringify”

Leave a Comment