0

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!

asked Jul 17, 2011 at 12:18
2
  • $H()... is that Prototype? BTW, do not use eval() like that, it's a gaping security hole and source of bugs. Commented Jul 17, 2011 at 12:21
  • Also, I think $H() expects an object as input, not a list. Commented Jul 17, 2011 at 12:32

4 Answers 4

3

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.

answered Jul 17, 2011 at 12:23
Sign up to request clarification or add additional context in comments.

2 Comments

The "$H()" thing is almost certainly from the Prototype framework.
Thanks for the JSON.parse() tip.
1

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);
});
answered Jul 17, 2011 at 12:24

Comments

1

Avoid framework features when you need simple things.

for(i=0; i<recommendedList.length; i++) { 
 alert(recommendedList[i].artist);
}
answered Jul 17, 2011 at 12:29

Comments

0

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);
 }); 
answered Jul 17, 2011 at 12:21

1 Comment

@Pointy: I'm not sure but I was trying to point out what was happening. Your solution is preferable indeed.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.