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

3 Answers 3

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);
            });
        }
    });
});
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

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
thanks all but it's not working for me. i try @john S answer and it working :)
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);
        }

    });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.