Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop and get key/value pair for JSON array using jQuery

I'm looking to loop through a JSON array and display the key and value.

It 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 the 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 it 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);         }); 

There is no mandatory jQuery requirement, but it is available. I can also restructure the JSON if it cuts down the required code.

like image 807
JStark Avatar asked Oct 22 '11 16:10

JStark


2 Answers

You have a string representing a JSON serialized JavaScript object. You need to deserialize it back to 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.

like image 143
Darin Dimitrov Avatar answered Sep 28 '22 03:09

Darin Dimitrov


var obj = $.parseJSON(result); for (var prop in obj) {     alert(prop + " is " + obj[prop]); } 
like image 34
xdazz Avatar answered Sep 28 '22 03:09

xdazz