Jquery getJSON sorts my data by id automatically

gabo84 picture gabo84 · Sep 25, 2012 · Viewed 11.3k times · Source

I have a combo box that triggers a jquery function on change, it calls a php script which brings the results from the database sorted by name not by id (table cities) and creates a json file with the id and the name of the city. The problem comes with a $.getJSON(url, data) function, it retrieves all the json encoded data fine, but it is seems to be sorting the data automatically by the id

for instance if the php page generates

id  name
3   Dania Beach
1   Miami
2   Weston

after jquery getJSON it sorts it by id

id  name
1   Miami
2   Weston
3   Dania Beach

Is there a way to disable sorting? or how can in preserve the order by name?

Answer

Joe Coder picture Joe Coder · Sep 25, 2012

This is an associative array: order does not matter. The following JSON objects are equivalent:

{
    "3" : "Danie Beach",
    "1" : "Miami",
    "2" : "Weston"
}

{
    "1" : "Miami",
    "2" : "Weston",
    "3" : "Danie Beach"
}

If you need an ordering, you should instead embed an array within the JSON:

{
    "beaches" : [
        {"key" : "3", "value" : "Danie Beach"},
        {"key" : "1", "value" : "Miami"},
        {"key" : "2", "value" : "Weston"}
    ]
}

Example Usage:

jQuery.ajax({
    ...
    dataType: 'json',
    success: function(data) {
        jQuery.each(data.beaches, function(i, beach) {
            alert(i+': beach['+beach.key+'] = '+beach.value);
        });
    }
});