Prateek
Prateek

Reputation: 1220

How can iterate a json object string with jquery

I have web service which return json string like : d={"main0ID":"abc.es/main","main1ID":"ah/main"} I wanna append this to ul HTML control. How to iterate over json object string and append to ul?

Thanks...

Upvotes: 1

Views: 412

Answers (6)

Prateek
Prateek

Reputation: 1220

$("#Button1").click(function () {
WebService.GetList(OnComplete, OnError);
function OnComplete(result) 
{
var items = "";
var value = Sys.Serialization.JavaScriptSerializer.deserialize(result, true);
for (var property in value) 
{              
items += "<option value='" + value[property] + "'>" + value[property] + "</option>";
}
$("#ContentPlaceHolder1_ListBox1").html(items);
}
function OnError(err)
{
alert("The error is :" + err.get_Message());
}
});

Upvotes: 0

Wasim Karani
Wasim Karani

Reputation: 8886

Both this methods can be used
But first method is considerably fast...

Check this tutorial ...

for (var keyIndex in d) {
    console.log(keyIndex, d[keyIndex]);
}

$.each(data,function(keyIndex,value){
    console.debug(inkeyIndexex,value);
});

Upvotes: 1

Shyju
Shyju

Reputation: 218722

Assuming you have ul like this

<ul id="ulItems"></ul>      

This will get the items from JSON and add to UL

$(function(){
    var items="";
    var data={"main0ID":"abc.es/main","main1ID":"ah/main"}
       $.each(data,function(index,item){
         items+="<option value='"+item+"'>"+item+"</option>";
       });       
    $("#ulItems").html(items);
});

Working sample : http://jsfiddle.net/tFpTu/4/

Always build a string and call the html function only once instead of calling the append function n times inside a loop

Upvotes: 1

coolguy
coolguy

Reputation: 7954

    $.ajax({           
                url: 'your url'
                type : 'POST',
                data : {/*any data*/},
                dataType:'json',
                success: function(msg) { //your json return
                for (i=0;i<msg.length;i++){
       alert(msg[i]['your_index']);
}

}

Upvotes: 1

Vinayak Phal
Vinayak Phal

Reputation: 8919

You can use .each() or .map() to iterate over the json object.

Upvotes: 1

xdazz
xdazz

Reputation: 160833

You could use for..in to iterate an object.

for (var key in d) {
  console.log(key, d[key]);
}

Upvotes: 3

Related Questions