Best way to parse Json?

I want to parse the data from a json and replace them in a table. And I'm using following code

var obj=$.parseJSON(data);
data=obj.data;
totalRecord=obj.totalCount;
$.each(data,function(i,obj){
  for(var j in obj){
    switch(j){
            case 'priority':
                $("#td_"+i+"_"+j).find('.priority').val(obj[j]);
                $("#td_"+i+"_"+j).find('.hidden').val(obj['id']);
                break;
            case 'chkbox':
                $("#td_"+i+"_"+j).find('.chkbox').val(obj['id']);
                break;
            case 'status':
                var val=(this.j)?'active.gif':'deactive.gif';
                $("#td_"+i+"_"+j).find('img').attr('src','<?= base_url() ?>assets/grid/images/'+val);
                $("#td_"+i+"_"+j).find('img').attr('onClick','updateStatus(\''+obj['id']+'\',\''+obj[j]+'\')');
                break;
            case 'edit':
                $("#td_"+i+"_"+j).find('a').attr('href','index.php/main/edit/'+obj[j]);
                break;
            default:
                $("#td_"+i+"_"+j).html(obj[j])
                break;
            }
  }
});

But i think its bit slow. Is there other better ways to implement the same?

KrishNik

Answers


I'm not sure it's the parsing that's slowing you down. It could be that you're running a lot of jQuery selectors on a lot of objects, which can take time.

EDIT: Saw @pointy's answer. I didn't even notice that you were doing event delegation via DOM attributes. Yeeaah, that would probably run pretty slowly.

In fact, using live event delegation instead of assigning a click event to every single element would probably run even faster. Start by, instead of giving it the click event, give the element a reference to the object in question using jQuery's data function.

case 'status':
    // Note that I switched it to this[j], since I suspect
    // using this.j was unintentional
    var val=(this[j])?'active.gif':'deactive.gif';
    $('#td_'+i+'_'+j).find('img').attr('src', '<?= base_url() ?>assets/grid/images/'+val).
        data('status_obj', obj);

Then, run the following only once in your entire script (obviously, untested).

$('td.status img').live('click', function () {
    var obj = $(this).data('status_obj');
    updateStatus(obj.id, obj.status);
});

This means that any img inside a td.status element (yep, I made up a new class name for you) that ever exists will, upon being clicked, run updateStatus with that status_obj data stored inside it.

Some smaller optimizations:

  • Specify a tag name when looking up children, e.g. find('span.priority'), since jQuery can then loop through only children of that tag name instead of all children
  • Or, in fact, give those children their own unique IDs to look up by, since getElementById is almost certain to run faster than looping through children.

First, your JSON is parsed by that call to $.parseJSON(), and I bet that's not slow. I bet that what is slow is the code that interprets the data structure and updates your DOM.

The first thing you need to do is stash that jQuery lookup in the inner loop. That'll help a little:

   for (var j in obj) {
     var cell = $('#td_' + i + '_' + j);

Now you can use "cell" instead of repeating that jQuery lookup. (Won't help that much, but it's something.)

For setting up event handlers in a (potentially large) table, when what you want to handle are clicks (or whatever) on individual cells, you'd be much better off using jQuery's .delegate() function:

  case 'status':
    $('table').delegate('#td_' + i + '_' + j, 'click', function() {
      updateStatus(obj['id'], obj[j]);
    });
    break;

Note that your current code will re-attach that "onClick" handler each time it receives a "status" message in the data. You could add a check to make sure you don't needlessly re-register that:

  case 'status':
    if (!$('table').data(i + '_' + j)) {
      $('table').delegate('#td_' + i + '_' + j, 'click', function() {
        updateStatus(obj['id'], obj[j]);
      });
      $('table').data(i + '_' + j, true);
    }
    break;

No matter how you roll it, iterating over a big data structure and updating lots of cells in a big table can be pretty slow, depending on your CSS etc and especially in old browsers (IE6).


You are locating each elements for every iteration in the loop. Locate the cell and put the result in a variable outside the loop.

var obj = $.parseJSON(data);
var parsedData = obj.data;
var totalRecord = obj.totalCount;
$.each(parsedData, function(i, item) {
  for(var j in item) {
    var element = $("#td_"+i+"_"+j);
    switch(j) {
      case 'priority':
        element.find('.priority').val(item[j]);
        element.find('.hidden').val(item['id']);
        break;
      case 'chkbox':
        element.find('.chkbox').val(item['id']);
        break;
      case 'status':
        var val=(this.j)?'active.gif':'deactive.gif';
        element.find('img')
          .attr('src','<?= base_url() ?>assets/grid/images/'+val)
          .attr('onClick','updateStatus(\''+item['id']+'\',\''+item[j]+'\')');
        break;
      case 'edit':
        element.find('a').attr('href','index.php/main/edit/'+item[j]);
        break;
      default:
        element.html(item[j])
        break;
      }
    }
  });

Note that I renamed some variables. You were reusing variable names for different things, like reusing the data variable containing the JSON string to contain the parsed data, and the obj variable that contains the parsing result to contain a single item from the data.

I notices that you are using this.j at one point in the code. This is not the same as item[j] but item['j'], which might not be what's intended.


Need Your Help

Grep search for redirects in .htaccess

linux .htaccess grep putty

I have here code for search all .htaccess files in all folders and subfolders

Visual Basic Iterating Over a ListBox with an Event Listener

.net vb.net

I have a ListBox Containg a list of items,i am wondering how would i create a handler which can Iterate the ListBox whenever an event is happen.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.