12

I'm getting a JSON response from the server and i have to loop through the array in javascript and get the values. But I cant seem to loop throught it.

The JSON response of the array looks like this:

{
   "1": "Schools",
   "20": "Profiles",
   "31": "Statistics",
   "44": "Messages",
   "50": "Contacts"
}

I just want to loop through it to get the ID and Name and populate some values on the page.

I have tried:

$.each(response, function(key, value) {
    alert(key + ' ' + value);
});

// and 

for (var key in response) {
    alert(key + ' ' + response[key]);
}

But neither give the right values.

Thanks in advance for any help.

Reply: Hi, The response I'm getting with the second loop is:

0 {
1 "
2 1
3 "
4 :
5 "
6 S

etc etc

So that means its going through the whole response as a string and spliting it as key/value.

Thanks

6
  • 1
    What "wrong values" are you getting? Commented May 18, 2011 at 15:50
  • What happens when you try these (seemingly correct) strategies? You'll get better answers if you include the erroneous values... Commented May 18, 2011 at 15:51
  • 1
    Your second example works fine : jsfiddle.net/vgvw9 What exactly does not work? Commented May 18, 2011 at 15:53
  • The response I'm getting with the second loop is: 0 { 1 " 2 1 3 " 4 : 5 " 6 S etc etc So that means its going through the whole response as a string. Commented May 18, 2011 at 16:12
  • please post the code showing how you get the response object. That seems to have values other than what you are expecting.. Commented May 18, 2011 at 17:25

6 Answers 6

21

Your problem is that you are not parsing the JSON string. Therefore, your foreach is going through the characters in the JSON string.

// If you are using jQuery.ajax, you can just set dataType to 'json' 
// and the following line will be done for you
var obj  = jQuery.parseJSON( response );
// Now the two will work
$.each(obj, function(key, value) {
    alert(key + ' ' + value);
});


for (var key in obj) {
    alert(key + ' ' + response[key]);
}
Sign up to request clarification or add additional context in comments.

2 Comments

if the url you are pulling data from is hosted on a different site, you need to make sure the data is being json encoded on their end and change the dataType to 'jsonp'. jQuery adds a Callback hash to the request so it knows which function to return the result to. Keep in mind the 3rd party must be json_encoded or the mime-type will be incorrect when the callback is made.
@DaveCottrell That seems completely unrelated to the question itself, not sure why you felt the need to add the comment. Sure there are cross domain concerns, but the OP is not asking about that, they had forgotten to parse the JSON, you're just adding noise...
2
var response = {"1":"Schools","20":"Profiles","31":"Statistics","44":"Messages","50":"Contacts"};

for (var i in response) {
    console.log(i + ' ' + response[i]);
}

Works just fine, how are you getting your response var?

Comments

2

You don't need to do like that, dealing with string is a boring job. You can make a object through the response. 1:json = eval(xmlHttp.responseText);

but this is unsafe in some degree.

  1. json = JSON.parse(xmlHttp.responseText, function(key,value){// can do some other stuff here.});

then you can operate the variable as a normal object like this obj.a or obj["a"].

May this will help you.

Comments

1

http://jsfiddle.net/sG5sF/

jQuery.each works fine. So is for-each loop

http://jsfiddle.net/TfjrS/

Both of them work as they should. You might have errors in other parts of your code. Is the response variable set correctly to the JSON object given in your question? Are you checking the response statusCode? it should be 200 for a successful response?

Comments

0

Consider looking at How can I parse a JavaScript object with jQuery for a possible answer.

Comments

0

You can use for-in construct in pure Javascript. Of course, you need to be careful that you're only looking at the object's own properties (libraries like Prototype tend to pollute):

for(var key in response) {
    if(response.hasOwnProperty(key)) {
       ...
    }
}

EDIT

Are you using jQuery.ajax? What's the dataType value? It should be json. This might be why your response is being interpreted as a string. Also, when you console.log response, does it show up as a string or an object?

6 Comments

@Vivin: Why do you use hasOwnProperty? Are you using Prototype or another library that augments Object's prototype? Otherwise, a literal object will only loop through the values in the JSON.
@JuanMendes: It's something I do just to be safe (I'm probably just being paranoid). If you're sure that you're never going to use a library that pollutes the namespace, then there is no need for the hasOwnProperty.
@Vivin Paliath: It's a pretty bad trade-off, "I'm going to wrap all my loops with hasOwnProperty because I may one day use a library that augments Object.prototype". Even Prototype stopped doing it because they saw how bad it was (were forced to). I think that's a silly safety valve. Same evil as premature optimization. If a library augments native objects, I stay away from it, not many libs do nowadays. Think YAGNI en.wikipedia.org/wiki/You_ain't_gonna_need_it. Also, for SO examples, you should keep them as slim as possible.
@JuanMendes, I don't think it's a bad trade-off. I don't use prototype as much on my own, but at work it's in our library and causes all sorts of problem. Also, if you're writing your own library and intend to distribute it, then you will need to do something like this since you cannot predict the environment it will run in. People can and will pollute the namespace. Of course, it depends on the situation. If you can be sure that there will be no namespace pollution then you don't need to wrap it. A blanket statement saying "don't use it at all" is just as bad as saying "use it all the time".
@Vivian: I didn't say "don't use it at all", I said "don't use it all the time" as you said you did! If you don't want to look at inherited properties, then use it. You're really masking a problem, and assuming that there is "namespace polution" (better known as "native object prototype augmentation".) If I were to write a lib that needed to loop through object properties, I would say in big bold letters, not compatible with augmenting Object.prototype since the object that is passed in may inherit another object. How could you assume you should never iterate through inherited properties?
|

Your Answer

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.