Browse and read JSON with jQuery - for and $.each
Let's go through this simple example of jQuery to browse an array of JavaScript objects.
var json = [The execution of this example runs correctly and the cities are displayed in an alert box. A common problem with declaring a string JSON with a single or double quottes.
{"id":"1","text":"paris"},
{"id":"2","text":"marseille"},
{"id":"3", "text":"Lille"},
{"id":"4","text":"Metz"},
{"id":"5","text":"renne"}
];
$.each(json, function(i, obj) {
alert(obj.text);
});
var json = '[{"id":"1","city":"paris"},{"id":"2","city":"marseille"},Chrome browser displays this error in console:
{"id":"3","city":"lille"},{"id":"4","city":"metz"},
{"id":"5","city": "reindeer"}]';
$.each(json, function(i, obj) {
alert(obj.city);
});
Uncaught TypeError: Cannot use 'in' operator to search for ...The ideal solution is to convert JSON to a JavaScript object with the JSON.parse() function or the jQuery function $.parseJSON.
in [{"id":"1","ville":"paris"}...
$.each(JSON.parse(json), function(i, obj) {
alert(obj.ville);
});
//ou
$.each($.parseJSON(json), function(i, obj) {
alert(obj.city);
});
JSON example and the JavaScript loop for
The following example shows how to iterate through a JSON object using the JavaScript for loop.
< head>
< meta charset="utf-8">
< title> Example of the javascript for and JSON loop
< script src="https://code.jquery.com/jquery-1.10.2.js">
< body>
< script>
$(function() {
var data = [
{"id":"1","name":"One"},
{"id":"2","name":"Two"},
{"id":"3","name":"Three"},
{"id":"4","name":"Four"},
{"id":"5","name":"Five"}
];
var data_length = data.length;
for (var i = 0; i < data_length; i++) {
alert(data[i]["id"] + " " + data[i]["name"]);
}
});