How to read an external local JSON file in JavaScript?

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

    You must create a new XMLHttpRequest instance and load the contents of the json file.

    This tip work for me (https://codepen.io/KryptoniteDove/post/load-json-file-locally-using-pure-javascript):

     function loadJSON(callback) {   
    
        var xobj = new XMLHttpRequest();
            xobj.overrideMimeType("application/json");
        xobj.open('GET', 'my_data.json', true); // Replace 'my_data' with the path to your file
        xobj.onreadystatechange = function () {
              if (xobj.readyState == 4 && xobj.status == "200") {
                // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
                callback(xobj.responseText);
              }
        };
        xobj.send(null);  
     }
    
     loadJSON(function(response) {
        // Parse JSON string into object
        var actual_JSON = JSON.parse(response);
     });
    

提交回复
热议问题