Does JSON.stringify preserves order of objects in array

You can sort arrays using sort method.

And yes stringify retains ordering.

jsfiddle

var cars = ["Saab", "Volvo", "BMW"];
cars.push("ferrari");
alert(JSON.stringify(cars));
cars.sort();
alert("sorted cars" + JSON.stringify(cars));

There is nothing in the docs that explicitly confirms that the order of array items is preserved. However, the docs state that for non-array properties, order is not guaranteed:

Properties of non-array objects are not guaranteed to be stringified in any particular order. Do not rely on ordering of properties within the same object within the stringification.

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

Even if the order of array items would be preserved, I would not count on this but rather sort the items myself. After all, there will most likely be some business or presentation logic that indicates how the items should be sorted.


For a simple way to get top level objects in a specific order from JSON.stringify() you can use:

const str = JSON.stringify(obj, Object.keys(obj).sort());

The order of the keys [] passed as the replacer determines the order in the resulting string.

See: https://dev.to/sidvishnoi/comment/gp71 and "sort object properties and JSON.stringify" - https://www.tfzx.net/article/499097.html

Another more rigorous approach is: https://github.com/develohpanda/json-order

And:https://www.npmjs.com/package/fast-json-stable-stringify will output in key order. You can also use your own sort order function.

I found this after lots of Google'ing.