How to read an external local JSON file in JavaScript?

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

    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.

提交回复
热议问题