Coder Perfect

In JavaScript, how can I read an external local JSON file?

Problem

I’ve saved a JSON file on my local PC and written a JavaScript file to read it and report data from it. The JSON file is as follows:

{"resource":"A","literals":["B","C","D"]}

Let’s imagine the JSON file’s path is /Users/Documents/workspace/test.json.

Could anyone please help me write a simple piece of code to read the JSON file and print the data in JavaScript?

Asked by user2864315

Solution #1

To use javascript to read an external Local JSON file (data.json), first construct your data.json file:

data = '[{"name" : "Ashwin", "age" : "20"},{"name" : "Abhinandan", "age" : "20"}]';

See this link for further details.

Answered by Ashfedy

Solution #2

Because loading a.json file from disk is an asynchronous process, a callback function must be specified to run after the file has been loaded.

function readTextFile(file, callback) {
    var rawFile = new XMLHttpRequest();
    rawFile.overrideMimeType("application/json");
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function() {
        if (rawFile.readyState === 4 && rawFile.status == "200") {
            callback(rawFile.responseText);
        }
    }
    rawFile.send(null);
}

//usage:
readTextFile("/Users/Documents/workspace/test.json", function(text){
    var data = JSON.parse(text);
    console.log(data);
});

By setting the mime type option to “text/html”, “text/plain”, and so on, this function can also load.html or.txt files.

Answered by Stano

Solution #3

Because the request is made using HTTP, you can’t make an AJAX call to a local resource.

Run a local webserver, serve the file, and make the AJAX call to localhost as a workaround.

You should study the jQuery documentation to help you develop code that reads JSON. getJSON():

http://api.jquery.com/jQuery.getJSON/

Answered by Chris Pickford

Solution #4

You can just do the following in Node.js or require.js in the browser:

let json = require('/Users/Documents/workspace/test.json');
console.log(json, 'the json obj');

It’s worth noting that the file is only loaded once; subsequent calls will rely on the cache.

Answered by musicformellons

Solution #5

The simplest method is to use the Fetch API:

fetch("test.json")
  .then(response => response.json())
  .then(json => console.log(json));

It works perfectly in Firefox, however you must change the security settings on Chrome.

Answered by Alex Glinsky

Post is based on https://stackoverflow.com/questions/19706046/how-to-read-an-external-local-json-file-in-javascript