$.getJSON("sample.json", function(json) {
$.getJSON
gets a json document called "sample.json", this document is allocated in the "json" variable wich is inside your function.
json.forEach(function(val) {
As JSON is "JavaScript Object Notation", we know that your variable json is an object, that's why you can use the function Object.forEach()
, It works as a for..in..
,
var keys = Object.keys(val);
Object.keys(val)
here, your variable val must be an object or array, and this method will return all the indexes in your object/array (val), therefore, all the indexes inside the json you bringed in the document "sample.json", will be added to your variable keys
.
For example:
$.getJSON("/json/sample.json", function(json) {
var html = "";
json.forEach(function(val) { // Iterates in the json
var keys = Object.keys(val); // Assignes the indexes to the var keys
html += "<div>"; // Opens and appends a div element
keys.forEach(function(key) { // Appends the element of the object/array at each index (key)
html += "<strong>" + key + "</strong>"
});
html += "</div><br>"; // Closes the div element and starts a new line
});