How to read an external local JSON file in JavaScript?

前端 未结 22 1935
醉酒成梦
醉酒成梦 2020-11-22 02:53

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:

{"res         


        
22条回答
  •  抹茶落季
    2020-11-22 03:01

    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.

      
      
      
    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.

提交回复
热议问题