Loading of JSON file by javascript is simple. Moreover, it can be done without using of JQuery at all. This tutorial will show you how to accomplish the mission easily.
Let’s start by creating a JSON file with the following content. Save the filename as “data.json”.
1 |
data = '[{"name" : "Harry", "age" : "32"}]'; |
Let’s create a javascript file to read the json data as following. Save the javascript file as “myscript.js”.
1 2 3 4 5 |
function load() { var mydata = JSON.parse(data); alert(mydata[0].name); alert(mydata[0].age); } |
We are yet to complete the tutorial. Still we need to load both files in the html file that we are going to create now. Create a HTML file as following:
1 2 3 4 5 6 7 8 9 10 11 |
<!doctype html> <html> <head> <title>askyb - Load JSON File Locally by Javascript Without JQuery</title> <script type="text/javascript" src="file.json"></script> <script type="text/javascript" src="myscript.js"></script> </head> <body onload="load()"> askyb - Load JSON File Locally by Javascript Without JQuery </body> </html> |
Save the HTML file as “test.html”.
Run the HTML file in your browser and you will observe the following output:
Your .json file isn’t actually a JSON document — it’s a JavaScript one. This technique won’t work for true JSON files. Try replacing the content of your file.json with:
[{"name" : "Harry", "age" : "32"}]
Drew’s right but it’s not actually that difficult to load a JSON file local or otherwise with pure JS.
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'file.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// .open will NOT return a value but simply returns undefined in async mode so use a callback
callback(xobj.responseText);
}
}
xobj.send(null);
}
// Call to function with anonymous callback
loadJSON(function(response) {
// Do Something with the response e.g.
//jsonresponse = JSON.parse(response);
// Assuming json data is wrapped in square brackets as Drew suggests
//console.log(jsonresponse[0].name);
});
You just create JSON script variable, not JSON file.
Thanks for the true script, Rich.