Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm looking to loop through a JSON array and display the key and value. Should be a simplified version of the following post but I don't seem to have the syntax correct: Jquery each loop with json array I also saw this post Get name of Key in Key/Value Pair in JSON using jQuery? but it also seemed like lots of code for a simple activity.

This illustrates what I'm looking for (but doesn't work):

var result = '{"FirstName":"John","LastName":"Doe","Email":"[email protected]","Phone":"123 dead drive"}';
$.each(result, function(k, v) {
             //display the key and value pair
            alert(k + ' is ' + v);
        });

No manditory jQuery requirement, but it is available. I can also restructure the JSON if it cuts down the code required.

share|improve this question
2  
You have to parse JSON to a JavaScript object first. – Felix Kling Oct 22 '11 at 16:49

2 Answers

up vote 10 down vote accepted

What you have is a string representing a JSON serialized javascript object. You need to deserialize it back a javascript object before being able to loop through its properties. Otherwise you will be looping through each individual character of this string.

var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"[email protected]","Phone":"123 dead drive"}';
var result = $.parseJSON(resultJSON);
$.each(result, function(k, v) {
    //display the key and value pair
    alert(k + ' is ' + v);
});

Live demo.

share|improve this answer
Excellent. I added var result = $.parseJSON(resultJSON); and now it works. – JStark Oct 22 '11 at 17:32
   var obj = $.parseJSON(result);
   for (var prop in obj) {
      alert(prop + " is " + obj[prop]);
   }
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.