Narazana
Narazana

Reputation: 1950

Extract some parts of JSON objects result

I'm trying to parse JSON result from an Ajax call to .NET web service like the following:

function doAjaxCallBack() {

      $.ajax({
           type: "POST",
           url: "AjaxCallBackService.asmx/GetAllTitles",
           contentType: "application/json; charset=utf-8",
           dataType: "json",
           success: function (msg) {

               // show alert book title and tags to test JSON result

           },

      });
}

Here's the JSON result I got back from doAjaxCallBack:

{"d":[
    {
        "__type":"ASP.NET_Training.Book",
        "Price":12.3,
        "Title":"Javascript Programming",
        "Tag":["Ajax","Javascript"]
    },
    {
        "__type":"ASP.NET_Training.Book",
        "Price":14.23,
        "Title":"Code Complete",
        "Tag":["Programming","Concept"]
    }
]}

I want to get book title and its tags. How do I loop over this kind of JSON?

Thank you.

Upvotes: 3

Views: 2358

Answers (3)

user113716
user113716

Reputation: 322452

You're getting back an Object with one property d, which references an Array of objects.

You can use the jQuery.each()[docs] method to iterate over that Array, and select the Title and Tag properties from each Object in the Array.

$.each(msg.d, function( i, val ) {
    console.log(val.Title);
    $.each(val.Tag, function( i, val ) {
        console.log("Tag: " + val);
    });
});

Live Example: http://jsfiddle.net/emSXt/3/ (open your console)

Upvotes: 3

Aravindan R
Aravindan R

Reputation: 3084

 $.each(msg.d, function( i, value ) {
 console.log(value.Title);
 if($.isArray(value.Tag)) {
     $.each(value.Tag, function(j, value1) {
         console.log(value1);
     });
 }else {
     console.log(value.Tag);
 }
});

Here's a fiddle http://jsfiddle.net/ATBNx/

Upvotes: 2

Julien
Julien

Reputation: 850

for(var ib in msg.d) {
  alert(msg.d[ib].Title);
  for(var it in msg.d[ib].Tag) {
    alert(msg.d[ib].Tag[it]);
  }     
}

Upvotes: 1

Related Questions