kmith
kmith

Reputation: 49

can't loop out data from json array?

I can't loop data out from response array.

$.post(myurl , function(response){
      for (var i = 0; i < response.result.length; i++) {
         alert(response.result[i]);
      }
},"json");

result of returned json array is :

{"result":["data one","data two","data three"]}

Upvotes: 0

Views: 283

Answers (2)

Ashwin Krishnamurthy
Ashwin Krishnamurthy

Reputation: 3758

  1. Did u try using JSON.parse to obtain your data in the JSON object format?
  2. Always use jslint to see if your JSON is proper, before using JSON.parse.

EDIT : In your head tag add json2.js. Go here and download it. Then whenever u have a json string like the one in your question. Just use JSON.parse(somejsonstring);

var t = '{"result":["data one","data two","data three"]}' ; //Response Text
var p = JSON.parse(t); //p.result[0] will give u "data one"

Upvotes: 0

Two-Bits
Two-Bits

Reputation: 51

You can iterate over an object's properties with a for each loop:

for (var prop in response) {
  alert(prop + ": " + response[prop]);
}

Upvotes: 1

Related Questions