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
+32.4k Golang : How to check if slice or array is empty?
+9.2k Golang : Allow Cross-Origin Resource Sharing request
+11.2k Golang : Listen and Serve on sub domain example
+4.7k Golang : Grab news article text and use NLP to get each paragraph's sentences
+6.1k Web : How to see your website from different countries?
+9.3k Golang : Generate 403 Forbidden to protect a page or prevent indexing by search engine
+10.8k Golang : Convert a rune to unicode style string \u
+6.3k Golang : alternative to os.Exit() function
+11.2k Golang : Arithmetic operation with numerical slices or arrays example
+7.6k Golang : Executing and evaluating nested loop in html template
+17.9k Golang : Clearing slice
+6.3k Golang : Create zip/ePub file without compression(use Store algorithm)