Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery's getJSON not maintaining original order

Tags:

json

jquery

Having the following file (customers.json):

{"3":"Andy", "1":"Bruce", "4":"Charlie", "2":"David"}

Using this code:

jQuery.getJSON("/Customers.json", function (data) {
    console.log(data);
});

This will output the following:

{"1":"Bruce", "2":"David", "3":"Andy", "4":"Charlie"}

My Json is purposefully in alphabetical order by the name, but this this code seems to put in numerical order. Is this a feature? And how do I stop this from happening?

Whether it makes a difference, I am using Firefox 39.0

EDIT:

The real question here is, is there anyway to do this, keeping ALL the data, and maintaining the order in which is received?

like image 450
gunwin Avatar asked Aug 07 '15 00:08

gunwin


2 Answers

What your Json SHOULD look like is

[{"id":"3", "name":"Andy"}, {"id":"1", "name":"Bruce"}, {"id":"4", "name":"Charlie"}, {"id":"2", "name":"David"}]

What you're sending is a series of objects (customers), so your data structure should ideally reflect that. And transferring it as an array you can keep the order, as has already been mentioned.

like image 165
Jan Avatar answered Oct 06 '22 23:10

Jan


is there anyway to do this, keeping ALL the data, and maintaining the order

Try utilizing $.map() , Array.prototype.sort() to return array of values , properties of returned object

var json = {
  "3": "Andy",
  "1": "Bruce",
  "4": "Charlie",
  "2": "David"
};
var res = $.map(json, function(val, key) {
  // keep all data, maintain order
  // return array having value as string with comma ","
  // as separator between `val` from object `key` from object
  // `val`: `Andy` , `key`: `3`
  return [ val + ", " + key ]
}).sort();
console.log(res);
document.body.textContent = res;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
like image 41
guest271314 Avatar answered Oct 06 '22 22:10

guest271314