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

I am looking for a loop through a JSON array and display the key and value.

This should be a simplified version of the following post, but I don't believe in the syntax: jQuery 'each' loop with a JSON array

I also saw the message Get key name in key / value pairs in JSON using jQuery? but it also seemed to contain a lot of code for a simple action.

This illustrates what I'm looking for (but this does not work):

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

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

+56
json javascript jquery
Oct 22 '11 at 16:46
source share
6 answers

You have a string representing a JSON serialized JavaScript object. You need to separate it before the JavaScript object before you can execute its properties. Otherwise, you will iterate over each individual character of this string.

 var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"johndoe@johndoe.com","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 .

+132
Oct 22 '11 at 16:49
source share
 var obj = $.parseJSON(result); for (var prop in obj) { alert(prop + " is " + obj[prop]); } 
+17
Oct 22 '11 at 16:49
source share

You can get the values ​​directly in the case of a single array like this:

 var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"johndoe@johndoe.com","Phone":"123 dead drive"}'; var result = $.parseJSON(resultJSON); result['FirstName']; // return 'John' result['LastName']; // return ''Doe' result['Email']; // return 'johndoe@johndoe.com' result['Phone']; // return '123' 
+6
Dec 30 '14 at 12:02
source share

The following should work for the returned JSON string. It will also work for an associative data array.

 for (var key in data) alert(key + ' is ' + data[key]); 
+5
Mar 03 '14 at 1:40
source share

Parse the JSON string and you can scroll through the keys.

 var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"johndoe@johndoe.com","Phone":"123 dead drive"}'; var data = JSON.parse(resultJSON); for (var key in data) { //console.log(key + ' : ' + data[key]); alert(key + ' --> ' + data[key]); } 
+2
May 23 '15 at 6:34
source share

The best and perfect solution for this problem:

I tried jQuery with answers to Ajax success, but it does not work, so I came up with my own and finally it works!

Click here to see the full solution.

 var rs = '{"test" : "Got it perfect!","message" : "Got it!"}'; eval("var toObject = "+ rs + ";"); alert(toObject.message); 
0
Jul 01 '13 at 19:21
source share



All Articles