DeLe
DeLe

Reputation: 2480

how to read multi-levels json format using jquery

i have a json format like

[
    {
        id: 15,
        diemdung: "a"
    },
    {
        id: "16",
        diemdung: "b",
        khoangcach: "300",
        pho: "c",
        da: [
            {
                lancan: "d",
                kc: "333"
            },
            {
                lancan: "e",
                kc: "322"
            }
        ]
    },
    ...
]

i using php like print json_encode($rows);
and i try to read it at client using jquery like

$.getJSON(url,function(json){
    $.each(json,function(key, val){
        $.each(this.da,function(){
            alert(this.kc);
        });
    });
});

but it's not working. How i do that? thanks

Upvotes: 1

Views: 1011

Answers (3)

Arvind
Arvind

Reputation: 938

For n level hierarchy

var str = '{"countries":[{"name":"USA","grandfathers":[{"gFName":"Steve","grandfathersKid":[{"gFKName": "Linda","kid": [{"name": "Steve JR", "friends": [{"name": "Kriss|John|Martin|Steven"}]}]}]}]}]}';
var obj = jQuery.parseJSON(str);
parseJsonString(obj);

Function :

function parseJsonString(data){       
    $.each(data, function(index, val){

        if($.type(val) == 'object' || $.type(val) == 'array'){
            product.parseJsonString(val);
        }else{
            alert(index + ' - ' + val);
        }

    });
}

Upvotes: 0

John S
John S

Reputation: 21492

If your code is otherwise working, you may be getting the following error:

TypeError: obj is undefined

This is because the first object in the outer array does not have a value for the "da" property. Before you try to loop over the array held by the "da" property, you should check if it exists.

Try:

$.getJSON(url,function(json){
    $.each(json,function(){
        if (this.da) {
            $.each(this.da,function(){
                alert(this.kc);
            });
        }
    });
});

Upvotes: 1

Jay Rizzi
Jay Rizzi

Reputation: 4304

 $.each(json, function(arrayID, arrayVal) {
  //alert(arrayVal.id);
  $.each(arrayVal.da, function(daKey,daData) {
   alert(daData.kc);
  });
 });

Heres my same SO question a while ago for further code

JQuery $.each() JSON array object iteration

edit to rename some variables to make clearer

Upvotes: 0

Related Questions