Advertisement
Advertisement


How to read an external local JSON file in JavaScript?


Question

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:

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

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 in JavaScript?

2020/07/26
1
266
7/26/2020 9:03:32 PM

Accepted Answer

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():

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

2013/10/31
93
10/31/2013 12:05:40 PM


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");
    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);
});

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

2018/09/06

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

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

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

2020/07/12

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

[{"name":"ay","id":"533"},
{"name":"kiy","id":"33"},
{"name":"iy","id":"33"},
{"name":"iy","id":"3"},
{"name":"kiy","id":"35"},
{"name":"kiy","id":"34"}]

  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');
console.log(words);
var express=require('express');

var app=express();

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

function listening(){
console.log("listening..");
}
app.use(express.static('website'));
app.use(bodyparser.urlencoded({extended:false}));
app.use(bodyparser.json());

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

 app.get('/get/:id',function(req,res){
 
var i;
   
 for(i=0;i<words.length;++i)
 {
 if(words[i].id==req.params.id){
 res.send(words[i]);
 }
}
console.log("success");
   
});

  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

 app.get('/get/:name',function(req,res){
 
var i;
   
 for(i=0;i<words.length;++i)
 {
 if(words[i].id==req.params.name){
 res.send(words[i]);
 }
}
console.log("success");
   
});

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

app.get('/get/name/:name',function(req,res){
word = words.filter(function(val){
  return val.name === req.params.name;
});
res.send(word);
    
 console.log("success");
   
});

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

app.get('/all',sendAll);
 
 function sendAll(request,response){
 response.send(words);

 }
 

2018/02/15

Using the Fetch API is the easiest solution:

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

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

2019/06/08


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 = e.target.result;
    // console.log(content);
    var intern = JSON.parse(content); // Array of Objects.
    console.log(intern); // You can index every object
  };
  fileread.readAsText(file_to_read);
});
2019/05/09