How to read an external local JSON file in JavaScript?

前端 未结 22 2307
醉酒成梦
醉酒成梦 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:16


    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"},
    ]
    


    
    

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

提交回复
热议问题