How to read an external local JSON file in JavaScript?

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, for instance. 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 with writing a simple piece of code to read the JSON file and print the data inside it in JavaScript?

Solutions/Answers:

Solution 1:

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/

Solution 2:

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);
    alert(mydata[0].name);
    alert(mydata[0].age);
    alert(mydata[1].name);
    alert(mydata[1].age);
    

For more information, see this reference.

Related:  Cannot set boolean values in LocalStorage?

Solution 3:

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.

Solution 4:

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

 }
 

Solution 5:

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.

Related:  javascript push multidimensional array

Solution 6:

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: http://www.html5rocks.com/en/tutorials/file/dndfiles/

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

var jsonData = JSON.parse(theTextContentOfMyFile);