Reputation: 507
I'm trying to retrieve some data from a JSON response, but this doesn't seem to work:
My javascript code:
function recommend(response){
var recommendedList = eval('(' + response.responseText + ')');
$H(recommendedList).each(function(item){
alert(item.artist);
});
}
What I want is to retrieve each artist values from the JSON response.
and the JSON response is of the format:
[
{"artist":"artist1","location":{"lat":"50.952226","lng":"5.34832","ID":28}},
{"artist":"artist2","location":{"lat":"52.362287","lng":"4.883965","ID":32}},
...
]
A little help would be great. Thanks!
Upvotes: 0
Views: 203
Reputation: 9256
Avoid framework features when you need simple things.
for(i=0; i<recommendedList.length; i++) {
alert(recommendedList[i].artist);
}
Upvotes: 1
Reputation: 154918
http://www.prototypejs.org/api/hash/each
Pairs are passed as the first argument of the iterator, in the form of objects with two properties:
key, which is the key name as a String
value, which is the corresponding value (and can, possibly, be undefined)
So your item
is actually the key. Instead, iterate like:
$H(recommendedList).each(function(key, item){
alert(item.artist);
});
Upvotes: 0
Reputation: 413884
Guessing from the "$H()" that you're using prototype, I'd just get rid of that "$H()" because the array should already be iterable.
recommendedList.each(function(item) {
alert(item.artist);
});
Upvotes: 1
Reputation: 54846
I'm not sure what your $H()
function is supposed to be doing (and its existence makes me very sad), but this framework-agnostic snippet seems to get the job done:
for (var index = 0; index < recommendedList.length; index++) {
alert(recommendedList[index].artist);
}
Here is a working example: http://jsfiddle.net/VgPy5/
Also, I'm sure you're going to be chastised for using eval()
like that. You might consider using JSON.parse() instead.
Upvotes: 3