How to read an external local JSON file in JavaScript?

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

    I liked what Stano/Meetar commented above. I use it to read .json files. I have expanded their examples using Promise. Here is the plunker for the same. https://plnkr.co/edit/PaNhe1XizWZ7C0r3ZVQx?p=preview

    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("DATA.json", function(text){
    //     var data = JSON.parse(text);
    //     console.log(data); 
    // });
    
    
    var task1 = function (){
      return new Promise (function(resolve, reject){
        readTextFile("DATA.json", function(text){
        var data = JSON.parse(text);
        console.log('task1 called');
        console.log(data);
        resolve('task1 came back');
        }); 
      });
    };
    
    var task2 = function (){
      return new Promise (function(resolve, reject){
        readTextFile("DATA2.json", function(text){
        var data2 = JSON.parse(text);
        console.log('task2 called');
        console.log(data2);
        resolve('task2 came back');
        });
      });
    }
    
    Promise.race([task1(), task2()])
           .then(function(fromResolve){
              console.log(fromResolve); 
           });
    

    The reading of JSON can be moved into another function, for DRY; but the example here is more of showcasing how to use promises.

提交回复
热议问题