Friday, November 25, 2011

JSON encode auto sorting issue

JSON is used to send data as an object either be an array or string.

I used AJAX to pass on my data from server to client. My intention was to populate a drop down list with values dynamically. I had created my array list as show below:
$result = array( '5' => 'a', '2' => 'b', '3' => 'c', '4' => 'd', );
echo json_encode(array( 'result' => 'success', 'details' => $result ));

I was expecting to see my array as is, but I was confused when I checked my JSON result array was as shown below:
array { result: "success", details: [{ 2: "b", 3: "c", 4: "d", 5: "a" }] }

See the problem? My array values were automatically sorted out. I found out that this is a browser issue with Google Chrome. I checked this using Firefox and there was no problem. So what is the solution to this problem? There are two ways:
  1. Don't use json_encode. I used this method because I realized I didn't really need to populate my dropdown list dynamically. I just needed static data for selection.
  2. Sort it out before appending to its drop down element.
  3. // data.details came from json_encode in the example above. 
    //arrVals should be an array.
    var arrVals = data.details();
    arrVals.sort(function(a, b){
        if(a.val>b.val){
            return 1;
        }   
        else if (a.val==b.val){
            return 0;
        }
        else {
            return -1;
        }
    });
    

Hopefully, Google Chrome will fix this bug so we won't encounter this again or performance will not be wasted.

Sources:
Sorting (dropdown) Select Options Using jQuery
Sort a select list box

1 comment: