Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JSON.stringify preserves order of objects in 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 );
}
message = {
      "employeeDetails" : myObjects 
}

After this I stringify them as follows

JSON.stringify(message);

Does the above method stringifies the objects in the order they were previously? After stringify will they be in the order 0,1,2....9 as they were previously?

like image 310
Arun Rahul Avatar asked Jun 16 '14 11:06

Arun Rahul


3 Answers

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.

like image 124
Christophe Herreman Avatar answered Sep 18 '22 23:09

Christophe Herreman


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.

like image 28
nevf Avatar answered Sep 20 '22 23:09

nevf


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));
like image 41
NimChimpsky Avatar answered Sep 22 '22 23:09

NimChimpsky