Javascript : How to loop over and parse JSON data?
This note is a short tutorial on how to loop over and parse JSON data with JQuery's each()
function and also show example on how to use JQuery's each()
function callback.
jQuery.each( array, callback )
In this example below, the callback function will treat the id as index and alphabet as object.
Here we go :
var jsonArray = [{
"id": "1",
"alphabet": "a"
}, {
"id": "2",
"alphabet": "b"
}, {
"id": "3",
"alphabet": "c"
}, {
"id": "4",
"alphabet": "d"
}, {
"id": "5",
"alphabet": "e"
}];
$.each(jsonArray, function(index, object) {
alert(object.alphabet);
});
Play at : http://codepen.io/anon/pen/JdeyZr
Sometimes, JQuery will complain(in console log) that the JSON array is not properly formatted. This is usually caused by malformed JSON string. To fix this issue, use the JQuery's parseJSON()
function to parse the JSON array.
$.each($.parseJSON(jsonArray), function(index, object) {
alert(object.alphabet);
});
References :
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+19.4k Golang : Measure http.Get() execution time
+24.9k Golang : convert rune to integer value
+11.1k Golang : Concatenate (combine) buffer data example
+22k Golang : Read directory content with filepath.Walk()
+25.9k Golang : Get executable name behind process ID example
+13.1k Golang : error parsing regexp: invalid or unsupported Perl syntax
+18.1k Golang : Get download file size
+34.1k Golang : Smarter Error Handling with strings.Contains()
+62.3k Golang : Convert HTTP Response body to string
+6.5k How to let Facebook Login button redirect to a particular URL ?
+19.1k Golang : How to count the number of repeated characters in a string?
+21.3k Golang : Convert string slice to struct and access with reflect example