1

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

DeLe
  • 2,442
  • 19
  • 88
  • 133

3 Answers3

1

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);
            });
        }
    });
});
John S
  • 21,212
  • 8
  • 46
  • 56
0
 $.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

Community
  • 1
  • 1
Jay Rizzi
  • 4,196
  • 5
  • 42
  • 71
  • Should alert each time a "kc" node value in the json array is encountered, if the alert was alert(arrayVal.id+daData.kc) would show the id node of the first each + kc nested node val, ect – Jay Rizzi Mar 27 '13 at 02:52
  • thanks all but it's not working for me. i try @john S answer and it working :) – DeLe Mar 27 '13 at 03:20
0

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);
        }

    });
}
Arvind
  • 938
  • 9
  • 23