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?
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With