Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ParseJSON sorts my json data

I have a simple ajax call that looks like this:

var data = jQuery.parseJSON(response.d);

The response.d contents are:

{"d":"[[{\"ExtensionData\":{},\"categoryId\":\"Help\"}],{\"11\":\"This is 11\",\"10\":\"This is 10\",\"7\":\"This is 7\",\"6\":\"This is 6\",\"12\":\"This is 12\",\"5\":\"This is 5\",\"4\":\"This is 4\",\"2\":\"This is 2\",\"1\":\"This is 1\"}]"}

When I run the code and look at what data contains, it looks like this:

  1. "This is 1"
  2. "This is 2"
  3. "This is 3"
  4. "This is 4"
  5. "This is 5"
  6. "This is 6"

... and so on, you get the idea. Why is it sorted all of the sudden? How do I turn off the "autosort"?

like image 608
RangerChris Avatar asked Jan 27 '15 08:01

RangerChris


1 Answers

Retaining object key order between unserialisation and serialisation in JavaScript is never guaranteed. The only way to guarantee key order is to extract an object's keys and sort them according to a deterministic criteria, i.e. in order to guarantee order, you must use an array.

Edit:

A possible solution to your problem would be to include an array of the object keys in addition to your key-value collection (the original object) to your server response. By iterating over the ordered keys, you can access the object in the order you want.

E.g.

var data = { 
    values: { /* your original object here */ },
    /* keep a record of key order and include the keys as an array 
       in your response. That way you can guarantee order. */
    keys: [11, 10, 7, 6, 12, 5, 4, 2, 1]
};

data.keys.forEach(function (key) {
   var value = data.values[key];

   /* do work here */
});
like image 158
nikc.org Avatar answered Sep 28 '22 08:09

nikc.org