How to read an external local JSON file in JavaScript?

I have saved a JSON file in my local system and created a JavaScript file in order to read the JSON file and print data out. Here is the JSON file:


Let’s say this is the path of the JSON file: /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 inside it in JavaScript?

You cannot make a AJAX call to a local resource as the request is made using HTTP.

A workaround is to run a local webserver, serve up the file and make the AJAX call to localhost.

In terms of helping you write code to read JSON, you should read the documentation for jQuery.getJSON():

For reading the external Local JSON file (data.json) using javascript, first create your data.json file:

data = '[{"name" : "Ashwin", "age" : "20"},{"name" : "Abhinandan", "age" : "20"}]';
  1. Mention the path of the json file in the script source along with the javascript file.

    <script type="text/javascript" src="data.json"></script>
    <script type="text/javascript" src="javascrip.js"></script>
  2. Get the Object from the json file

    var mydata = JSON.parse(data);

For more information, see this reference.

The loading of a .json file from harddisk is an asynchronous operation and thus it needs to specify a callback function to execute after the file is loaded.

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

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

This function works also for loading a .html or .txt files, by overriding the mime type parameter to "text/html", "text/plain" etc.

  1. First, create a json file. In this example my file is words.json


  1. And here is my code i.e,node.js. Note the 'utf8' argument to readFileSync: this makes it return not a Buffer (although JSON.parse can handle it), but a string. I am creating a server to see the result...

var fs=require('fs');
var data=fs.readFileSync('words.json', 'utf8');
var words=JSON.parse(data);
var bodyparser=require('body-parser');
var express=require('express');

var app=express();

var server=app.listen(3030,listening);

function listening(){

  1. When you want to read particular id details you can mention the code as..

var i;

  1. When you entered in url as localhost:3030/get/33 it will give the details related to that id....and you read by name also. My json file has simillar names with this code you can get one name details....and it didn't print all the simillar names

var i;

  1. And if you want to read simillar name details, you can use this code.

word = words.filter(function(val){
  return ===;

  1. If you want to read all the information in the file then use this code below.

 function sendAll(request,response){


When in Node.js or when using require.js in the browser, you can simply do:

let json = require('/Users/Documents/workspace/test.json');

Do note: the file is loaded once, subsequent calls will use the cache.

Using the Fetch API is the easiest solution:

  .then(response => response.json())
  .then(json => console.log(json));

It works perfect in Firefox, but in Chrome you have to customize security setting.

Depending on your browser, you may access to your local files. But this may not work for all the users of your app.

To do this, you can try the instructions from here:

Once your file is loaded, you can retrieve the data using:

var jsonData = JSON.parse(theTextContentOfMyFile);

If you are using local files, why not just packade the data as a js object?


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

No XMLHttpRequests, no parsing, just use MyData.resource directly

As many people mentioned before, this doesn't work using an AJAX call. However, there's a way around it. Using the input element, you can select your file.

The file selected (.json) need to have this structure:

    {"key": "value"},
    {"key2": "value2"},
    {"keyn": "valuen"},

<input type="file" id="get_the_file">

Then you can read the file using JS with FileReader():

document.getElementById("get_the_file").addEventListener("change", function() {
  var file_to_read = document.getElementById("get_the_file").files[0];
  var fileread = new FileReader();
  fileread.onload = function(e) {
    var content =;
    // console.log(content);
    var intern = JSON.parse(content); // Array of Objects.
    console.log(intern); // You can index every object

Very simple.
Rename your json file to ".js" instead ".json".

<script type="text/javascript" src="my_json.js"></script>

So follow your code normally.

<script type="text/javascript">
var obj = JSON.parse(contacts);

However, just for information, the content my json it's looks like the snip below.

contacts='[{"name":"bla bla", "email":bla bla, "address":"bla bla"}]';

Just use $.getJSON and then $.each to iterate the pair Key /value. Content example for the JSON file and functional code:

            "key": "INFO",
            "value": "This is an example."

    var url = "file.json";         
    $.getJSON(url, function (data) {
        $.each(data, function (key, model) {
            if (model.key == "INFO") {

You can use XMLHttpRequest() method:

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj = JSON.parse(this.responseText);
        //console.log("Json parsed data is: " + JSON.stringify(myObj));
    };"GET", "your_file_name.json", true);

You can see the response of myObj using console.log statement(commented out).

If you know AngularJS, you can use $http:

MyController.$inject = ['myService'];
function MyController(myService){

var promise = myService.getJsonFileContents();

  promise.then(function (response) {
    var results =;
    console.log("The JSON response is: " + JSON.stringify(results));
  .catch(function (error) {
    console.log("Something went wrong.");

myService.$inject = ['$http'];
function myService($http){

var service = this;

  service.getJsonFileContents = function () {
    var response = $http({
      method: "GET",
      url: ("your_file_name.json")

    return response;

If you have the file in a different folder, mention the complete path instead of filename.

You can import It like ES6 module;

import data from "/Users/Documents/workspace/test.json"

Since you have a web application, you may have a client and a server.

If you have only your browser, and you want to read a local file from a javascript that is running in your browser, that means that you have only a client. For security reasons, the browser should not let you do such thing.

However, as lauhub explained above, this seems to work:

Other solution is to setup somewhere in your machine a web server (tiny in windows or monkey in linux) and with an XMLHttpRequest or D3 library, request the file from the server and read it. The server will fetch the file from the local filesystem, and serve it to you through the web.

I liked what Stano/Meetar commented above. I use it to read .json files. I have expanded their examples using Promise. Here is the plunker for the same.

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

// readTextFile("DATA.json", function(text){
//     var data = JSON.parse(text);
//     console.log(data); 
// });

var task1 = function (){
  return new Promise (function(resolve, reject){
    readTextFile("DATA.json", function(text){
    var data = JSON.parse(text);
    console.log('task1 called');
    resolve('task1 came back');

var task2 = function (){
  return new Promise (function(resolve, reject){
    readTextFile("DATA2.json", function(text){
    var data2 = JSON.parse(text);
    console.log('task2 called');
    resolve('task2 came back');

Promise.race([task1(), task2()])

The reading of JSON can be moved into another function, for DRY; but the example here is more of showcasing how to use promises.

You must create a new XMLHttpRequest instance and load the contents of the json file.

This tip work for me (

 function loadJSON(callback) {   

    var xobj = new XMLHttpRequest();
        xobj.overrideMimeType("application/json");'GET', 'my_data.json', true); // Replace 'my_data' 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

 loadJSON(function(response) {
    // Parse JSON string into object
    var actual_JSON = JSON.parse(response);

One simple workaround is to put your JSON file inside a locally running server. for that from the terminal go to your project folder and start the local server on some port number e.g 8181

python -m SimpleHTTPServer 8181

Then browsing to http://localhost:8181/ should display all of your files including the JSON. Remember to install python if you don't already have.

If you could run a local web server (as Chris P suggested above), and if you could use jQuery, you could try

You could use D3 to handle the callback, and load the local JSON file data.json, as follows:

<script src="//" charset="utf-8"></script>

  d3.json("data.json", function(error, data) {
    if (error)
      throw error;

So, if you are planning to go with "Apache Tomcat" for hosting your JSON file,

1> After starting up the server, verify that your Apache Tomcat is up and running by going to this url: "localhost:8080" -

enter image description here

2> Next, go to the "webapps" folder - "C:\Program Files\Apache Software Foundation\Tomcat 8.5\webapps". And, create a project folder or copy your project folder.

enter image description here

3> Paste your json file over there. enter image description here

4> And that's it. You are done! Just go to - "http://localhost:8080/$project_name$/$jsonFile_name$.json"enter image description here

I took Stano's excellent answer and wrapped it in a promise. This might be useful if you don't have an option like node or webpack to fall back on to load a json file from the file system:

// wrapped XMLHttpRequest in a promise
const readFileP = (file, options = {method:'get'}) => 
  new Promise((resolve, reject) => {
    let request = new XMLHttpRequest();
    request.onload = resolve;
    request.onerror = reject;
    request.overrideMimeType("application/json");, file, true);
    request.onreadystatechange = () => {
        if (request.readyState === 4 && request.status === "200") {

You can call it like this:

readFileP('<path to file>')
    .then(d => {
      '<do something with the response data in d.srcElement.response>'

You can use d3.js to import JSON files. Just call d3 on your html body:

<script src=""></script>

Then put this on your js scripts:

  d3.json("test.json").then(function(data_json) {
         //do your stuff