Monday, August 6, 2012

Parsing Multidimensional Json array with jquery

How to parse following multidimensional json array with jquery 

{
   "data":{
     "item":[
         {
            "val1":58539,
            "val2":450000.0000,
            "Pictures":[
               {
   "Description":"",
                                    "Url":"http:\/\/demo1\/\/Pictures\/640\/58539_7f3a07a1dfe644228bed3378341c1e04.jpg"
               },
               {
                                    "Description":"",
                        "Url":"http:\/\/demo1\/\/Pictures\/640\/7730c8a5b65d4b75ba66dfafbde79a17.jpg"
               }
            ]
         },
         {
            "val1":58540,
            "val2":270000.0000,
            "Pictures":[
               {
                  "Description":"",
                  "Url":"http:\/\/demo1\/\/Pictures\/640\/58540_03035401.jpg"
               },
               {
                  "Description":"",
                  "Url":"http:\/\/demo1\/\/Pictures\/640\/58540_03035402.jpg"
               },
               {
                  "Description":"",
                  "Url":"http:\/\/demo1\/\/Pictures\/640\/58540_03035403.jpg"
               }             
            ],
         }
      ]
   }
}


Solution:


$.getJSON('url', function(data) {
      $.each(data.data.item, function() {
            var val1 = this.val1;
            var val2 = this.val2;
            $.each(this.Pictures, function() {
                  var desc = this.Description;
                  var url = this.Url;                
            });
      });
});

Example Reading from a JSON file 


create a file called test.json and use the below method 

 $.getJSON('test.json', function(data) {
            $.each(data.data, function() {
                var id = this.id;
                var headLine = this.headline
                var URL = this.originalURL;
                var Desc = this.extract;
                var country = this.article.country;
            });
        });

No comments:

Post a Comment