JSON Function Files
A common use of JSON is to read data from a web server, and display the data in a web page.
This chapter will teach you, in 4 easy steps, how to read JSON data, using function files.
JSON Example
This example reads a menu from myTutorials.js, and displays the menu in a web page:
JSON Example
<div id="id01"></div>
<script>
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i<arr.length; i++) {
out += '<a href="' + arr[i].url + '">' + arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>
<script src="myTutorials.js"></script>
Try it yourself »
Example Explained
1: Create an array of objects.
Use an array literal to declare an array of objects.
Give each object two properties: display and url.
Name the array myArray:
myArray
var myArray = [
{
"display": "JavaScript Tutorial",
"url": "http://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "http://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "http://www.w3schools.com/css/default.asp"
}
]
2: Create a JavaScript function to display the array.
Create a function myFunction() that loops the array objects, and display the content as HTML links:
myFunction()
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<a href="' + arr[i].url + '">' + arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
Call myFunction() with myArray as argument:
3: Use an array literal as the argument (instead of the array variable):
Call myFunction() with an array literal as argument:
Calling myFunction()
myFunction([
{
"display": "JavaScript Tutorial",
"url": "http://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "http://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "http://www.w3schools.com/css/default.asp"
}
]);
Try it yourself »
4: Put the function call in an external js file
Put the function call this in a file named myTutorials.js:
myTutorials.js
myFunction([
{
"display": "JavaScript Tutorial",
"url": "http://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "http://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "http://www.w3schools.com/css/default.asp"
}
]);
Add the external script to your page (instead of the function call):