How to read an external local JSON file in JavaScript?

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.

Leave a Comment