Reputation: 259
I have a webservice that returns a JSON object, but when I try to loop through it, each item in each object returns undefined
Here is the JSON object returned from the webservice
[{"result":14,"question":"6 - 7 مرات اسبوعيا","aID":70},{"result":29,"question":"3 - 5 مرات اسبوعيا","aID":71},{"result":41,"question":"مرة واحدة اسبوعيا","aID":72},{"result":14,"question":"1 - 3 مرات شهريا","aID":73}]
and here how I loop through it:
var resultAsJson = data.d;
$.each(resultAsJson, function (index, resObject) {
$('#pollResults').append('<p><strong>' + resObject.result + ' ' +
resObject.question + '</strong></p>');
alert(resObject.question);
});
------------------ UPDATE ------------------
hi Guys, the above code worked fine, the problem was the JSON response that I returned from the webservice was serialized as the following:
Dim m_result As New Data.Objects.ObjectParameter("Result", GetType(Boolean))
Dim lstofresult As List(Of addPollvote_Result) = Context.addPollvote(para_pid, para_aid, Date.Now, m_UID, Nothing, HttpContext.Current.Request.ServerVariables("REMOTE_ADDR"), Nothing, m_result).ToList
Dim m_json As New Script.Serialization.JavaScriptSerializer
Return m_json.Serialize(lstofresult)
When I removed the serialization and just returned the list, it worked perfect, see the below working code.
Dim m_result As New Data.Objects.ObjectParameter("Result", GetType(Boolean))
Dim lstofresult As List(Of addPollvote_Result) = Context.addPollvote(para_pid, para_aid, Date.Now, m_UID, Nothing, HttpContext.Current.Request.ServerVariables("REMOTE_ADDR"), Nothing, m_result).ToList
Return lstofresult
and it worked perfect.
Upvotes: 2
Views: 1363
Reputation: 603
The problem seems to be your datasource.
I would use a 'for' loop for testing purposes:
var resultAsJson = data.d;
var resultAsJsonLength = resultAsJson.length;
for(i=0;i<resultAsJsonLength;i++) {
$('#pollResults').append('<p><strong>' + resultAsJson[i].result + ' ' +
resultAsJson[i].question + '</strong></p>');
alert(resultAsJson[i].question);
}
You're going to have to provide more information about how you're accessing the data, which seems to be the foundation of your problem...
Upvotes: 0
Reputation: 16215
Make sure resultAsJson
is actually a JSON object and not a string and it should work (see this jsfiddle) - use resultAsJson = JSON.parse(resultAsJson)
to do the conversion from string to json object .
Upvotes: 2
Reputation: 19867
Give this a go. I assume you're using jQuery:
// The JSON String from the web service
var jsonString = '[{"result":14,"question":"6 - 7 مرات اسبوعيا","aID":70},{"result":29,"question":"3 - 5 مرات اسبوعيا","aID":71},{"result":41,"question":"مرة واحدة اسبوعيا","aID":72},{"result":14,"question":"1 - 3 مرات شهريا","aID":73}]';
// Parse the JSON string into a JS object
var jsonObj = JSON.parse(jsonString);
// Loop through, and pull what you need from it
$(jsonObj).each(function() {
console.log(this.result + " " + this.question);
});
Upvotes: 0