How to open a JSON local file in JavaScript

On occasions, while developing an application we need to load JSON file to load content like config/setting or data. These files can also exist in a directory tree structure.

There are various ways to achieve this and mostly people prefer the jQuery way. In this post, I will show you other methods along with the jQuery method to achieve the goal.

Note: Some of these methods are asynchronous and you will have to add some additional asynchronous handling code in your synchronous JavaScript.

Method 1: Using XHR

function loadFile(path, success, error)
{
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function()
    {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                if (success) {
                    success(JSON.parse(xhr.responseText));
                }
            } 
            else {
                if (error) {
                    error(xhr);
                }
            }
        }
    };
    
    xhr.open("GET", path, true);
    xhr.send();
}

And the function callee will look something like:

loadFile('config.json',
	function(response) { 
	  cfgdata = response; 
	},
	function(err) { 
	  console.error(err); 
	}
);

Method 2: Using $.getJSON

$.getJSON("test.json", function(json) {
    console.log(json); // output json file contents in browser console
});