0

i have nested json data. i used the blow function.

var jsonSource={"error_code":0, "ext_info":{"name":{"firstName":"John","lastName":"Jonson","nickName":"JJ"}}};
 var obj=JSON.parse(jsonSource),returnValue;

 function showJson(obj){

     for(var key in obj){
        if(typeof obj[key]==='object'){
            returnValue+='<div>'+key+'/\n';
            showJson(obj[key]);
            returnValue+='</div>';
         } else{
            returnValue+=key+'equal'+obj[key]; 
         }  
     }
   docoument.getElementById('data').innerHTML=returnValue;
 }

as i said before , i have a large nested json data and when i parse it to showJson function ,it just shows one level of json data and puts others deep level of dataJson undefined. what should i do to resolve the problem?

3 Answers3

0
    // obj is the object to loop, ul is the ul to append lis to
    function loop(obj, ul) {
        $.each(obj, function(key, val) {
            if(val && typeof val === "object") { // object, call recursively
                var ul2 = $("<ul>").appendTo(
                    $("<li>").appendTo(ul)
                );

                loop(val, ul2);
            } else {
                $("<li>").text(val).appendTo(ul);
            }
        });
    }
      var ul = $("<ul>");
      var jsonSource={"error_code":0, "ext_info":{"name":{"firstName":"John","lastName":"Jonson","nickName":"JJ"}}};
      var data=JSON.parse(jsonSource)
      loop(data, ul);

      ul.addClass("my-new-list").appendTo('body');
Prashant Agrawal
  • 660
  • 9
  • 24
  • thanks so much. i don't understand the part of your code:'... .....else{$('
  • ',{ id:key}).text(val).appendTo(ul); i mean {id:key}. what is it? and one more question. if i save the specific part of data , e.g just firstName, what should i do?
  • – Reza Asgari Feb 06 '16 at 12:53
  • Yeah you can ignore that (I have edited the answer). I didn't get your second part of the question though. Can you be more specific – Prashant Agrawal Feb 06 '16 at 13:23