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) {
            else {
                if (error) {
    };"GET", path, true);

And the function callee will look something like:

	function(response) { 
	  cfgdata = response; 
	function(err) { 

Method 2: Using $.getJSON

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