Contents hide 1) JavaScript Alternative To jQuery’s 1.1) The Improper Way 2) The correct method 2.1) – Create A New XMLHttpRequest 3) Usage 3.1) – Parse JSON string into object In this tutorial, we will see how to Load JSON file locally using pure Javascript. the proper way to include or load the JSON file in a web application, Instead of using JQuery we’ll The correct method using XMLHttpRequest JavaScript Alternative To jQuery’s Having a pure javascript alternative to jQuery’s $.getJSON() and $.parseJSON(). By far the main troublemaker is the belief that by including a .JSON file between the head tags of your HTML document you can access structured JSON. The Improper Way <script type="text/javascript" src="appDataServices.json"></script> Many examples will evidence that you can access the data with a simple function such as the one below. In fact, what this is not actually loading a JSON document but creating a Javascript object. This technique will not work for true JSON files. // 'JSON' data included as above data = '[{"Spider-man" : "is ok", "Need-For-Speed" : "Is My Favourate Game"}]'; // Function to 'load JSON' data function load() { var someData_notJSON = JSON.parse(data); console.log(someData_notJSON[0].Need-For-Speed); // Will log "Is My Favourate Game" } If you’re not particular about using an actual JSON file then creating a Javascript object in a separate .js file may be the way to go. If like me you do need to work with JSON in pure Javascript here’s what you’ll need to do. The correct method – Create A New XMLHttpRequest The clue here is the jQuery method $.getJSON() which is shorthand for $.ajax(). It may seem an odd way requesting a local file in this way but it offers the most flexibility with least confusion. function loadJSON(callback) { var xobj = new XMLHttpRequest(); xobj.overrideMimeType("application/json"); xobj.open('GET', 'appDataServices.json', true); // Replace 'appDataServices' with the path to your file xobj.onreadystatechange = function () { if (xobj.readyState == 4 && xobj.status == "200") { // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode callback(xobj.responseText); } }; xobj.send(null); } The function above will create a new instance of an XMLHttpRequest and load asynchronously the contents of appDataServices.json. I have gone with asynchronous but you can change the argument to false if you want a synchronous load. Thankfully all modern browsers support the native JSON.parse method. Remember our anonymous callback? here’s how you use it. Usage – Parse JSON string into object function init() { loadJSON(function(response) { // Parsing JSON string into object var actual_JSON = JSON.parse(response); }); } Get More Post On JavaScript Share this:TwitterFacebookRedditLinkedInWhatsAppPrintTumblr Related Tags: JavaScript, JQuery, js, json