August 4, 2012

Parsing JSON array of objects with jQuery

Question by Christopher Buono

What I am trying to do is parse this JSON: http://www.theunjust.com/test/container.php

And just get it to show at this point…

Here is my current code(its all jacked up)

$(document).ready(function(){
    var jsonurl = "container.php";
  $.getJSON(jsonurl, function(data) {         
    $.each(data.encompass,function(i,valu){
    var content,
    cont = '',
    tainers = valu.containers;

  $.each(tainers, function (i) {
    var tid = tainers[i].TID,
    top = tainers[i].Top,
    cat = tainers[i].Category,
    date = tainers[i].Date,
    icon = tainers[i].Icon,
    clink = tainers[i].ContainerLink,
    uid = tainers[i].UniqueID;

        cont += '<a href="' + clink + '">' + uid + '</a> ';
        $('ul').append('<li>' + tid + ' - ' + top + ' - ' + cat + ' - ' + date + ' - ' + icon + ' - ' + clink + ' - ' + uid + ' (' + cont + ')</li>');
    }); 
  }); 
}); 
});

I know that the code doesn’t make sense, this is more of a learning experience for me rather than a functioning tool. The issue may be in the JSON data itself, if that is the case, what stackoverflow web service post would you recommend?

What I eventually aim to do is run multiple web services and combine them… So that container.php loads and has all of the information that is required for a wrapping div, then entries.php loads and fills the divs that was generated by containers..

I’m currently learning jQuery and Honestly, I’m not to this level yet, but I am getting there pretty quick.

I really appreciate the help, and would like if you could point me in the direction to become a JSON parsing pro!

Answer by Starx

containers contain single node. So simply use

$.each(tainers, function (i, v) {
    var tid = v.TID,
    top = v.Top,
    cat = v.Category,
    date = v.Date,
    icon = v.Icon,
    clink = v.ContainerLink,
    uid = v.UniqueID;

    cont += '<a href="' + clink + '">' + uid + '</a> ';
    $('ul').append('<li>' + tid + ' - ' + top + ' - ' + cat + ' - ' + date + ' - ' + icon + ' - ' + clink + ' - ' + uid + ' (' + cont + ')</li>');
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!