Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

{"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?

like image 883
user2864315 Avatar asked Oct 31 '13 12:10

user2864315


People also ask

How do I access local JSON file?

Chrome allows you to access local JSON or other data files if you launch it with the --allow-file-access-from-files flag. I checked this with the code above on version 34.0. 1847.131 m; it should work on other versions as well.

Can JavaScript parse JSON natively?

JSON is a JavaScript-based object/value encoding format that looks very close to raw JavaScript and can be very easily parsed by JavaScript code because JavaScript can effectively evaluate a JSON string and re-materialize an object from it.


2 Answers

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"}]'; 

Then,

  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="javascript.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.

like image 138
Ashfedy Avatar answered Oct 13 '22 17:10

Ashfedy


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.

like image 31
Stano Avatar answered Oct 13 '22 15:10

Stano