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
+13.6k Golang : Tutorial on loading GOB and PEM files
+5.4k Golang : Display advertisement images or strings on random order
+16.7k Golang : Read integer from file into array
+23.7k Golang : Fix type interface{} has no field or no methods and type assertions example
+20.2k Swift : Convert (cast) Int to int32 or Uint32
+12.6k Golang : zlib compress file example
+4.1k Javascript : Empty an array example
+29.3k Golang : How to create new XML file ?
+18.2k Golang : Get path name to current directory or folder
+19.1k Golang : Delete item from slice based on index/key position
+16.8k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+21.1k Golang : How to force compile or remove object files first before rebuild?