Search code examples
javascriptjsonstringify

Does JSON.stringify preserve the order of objects in an array?


I am creating a JavaScript object as follows:

var myObjects; 
for (var i = 0; i < 10; i++) {
    var eachObject = {"id" : i};
    myObjects.push(eachObject);
}

var message = {
    "employeeDetails" : myObjects 
};

After this I stringify them as follows:

JSON.stringify(message);

Does the above method always stringify the objects in the order they were in previously?

After stringification, will they be in the order 0,1,2....9 as they were previously?


Solution

  • 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.