RangerChris
RangerChris

Reputation: 139

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"?

Upvotes: 6

Views: 10193

Answers (2)

nikc.org
nikc.org

Reputation: 16993

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 */
});

Upvotes: 13

Prabhu Vignesh Rajagopal
Prabhu Vignesh Rajagopal

Reputation: 1078

jQuery.parseJSON(); does not not sort your objects. But some browsers do sorting your objects after rendering. For clarification see here

Upvotes: -4

Related Questions