JQuery getJSON data order varies across browsers

JSON data:

{"2":"Alpha","1":"Beta"} 

The data format is fixed, i.e. I can't change it, I can only change the javascript / jQuery code.

  $.getJSON("www.myurl.com", function(data) { var items = []; $.each(data, function(key, val) { items.push(key + ', ' + val); }); alert(items); }); 

Display Chrome, IE9 and Opera: 1, Beta, 2, Alpha

Firefox and Safari mapping: 2, Alpha, 1, Beta p>

Question 1: What is correct?

Question 2: I want the data to be ordered in both Firefox and Safari. The easiest way to ensure Chrome, IE9 and Opera get the same result as Firefox and Safari?

+4
source share
3 answers

$.each works with javascript arrays (indexes are based on 0 bases). The JSON you showed is not an array. This is an associative array, which is that javascript object. So:

 $.getJSON("www.myurl.com", function(data) { var items = []; for (var prop in data) { if (data.hasOwnProperty(prop)) { items.push(prop + ', ' + data[prop]); } } alert(items); }); 

Or, if you want to use $.each , use arrays, for example:

 ["Alpha", "Beta"] 

and then:

 $.getJSON("www.myurl.com", function(data) { var items = []; $.each(data, function(index, element)) items.push(index + ', ' + element); } alert(items); }); 
+2
source

I don’t know ... but you can sort the array after the fact.

considering the following result (simulated for testing)

 var items = ["1, Beta", "2, Alpha"] 

You can

 items.sort(function(a,b){ return b.split(",")[0] - a.split(",")[0] }) 
+1
source

I would rebuild your answer to something like this:

 [ { "key":"2", "value":"Alpha" }, { "key":"1", "value":"Beta" } ] 

using an array, make sure the order is saved.

0
source

All Articles