How to read an external local JSON file in JavaScript?

前端 未结 22 1947
醉酒成梦
醉酒成梦 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 02:59

    You can use XMLHttpRequest() method:

        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var myObj = JSON.parse(this.responseText);
            //console.log("Json parsed data is: " + JSON.stringify(myObj));
           }
        };
    xmlhttp.open("GET", "your_file_name.json", true);
    xmlhttp.send();
    

    You can see the response of myObj using console.log statement(commented out).

    If you know AngularJS, you can use $http:

    MyController.$inject = ['myService'];
    function MyController(myService){
    
    var promise = myService.getJsonFileContents();
    
      promise.then(function (response) {
        var results = response.data;
        console.log("The JSON response is: " + JSON.stringify(results));
    })
      .catch(function (error) {
        console.log("Something went wrong.");
      });
    }
    
    myService.$inject = ['$http'];
    function myService($http){
    
    var service = this;
    
      service.getJsonFileContents = function () {
        var response = $http({
          method: "GET",
          url: ("your_file_name.json")
        });
    
        return response;
      };
    }
    

    If you have the file in a different folder, mention the complete path instead of filename.

提交回复
热议问题