简体   繁体   中英

How to load json file content to variable

I have json file in my file system. Is there any way to load content into variable?

I tried this:

vm.timeZones = require("timezones.json");

but it gives this error:

ReferenceError: require is not defined

jQuery.getJSON() should help.

Link for reference: JQuery.getJSON

$.getJSON("test.json", function(json) {
    console.log(json); // this will show the info it in firebug console
});


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

function init() {
loadJSON(function(response) {
  // Parse JSON string into object
   var actual_JSON = JSON.parse(response);
 });
}

Probably not.

If you were reading the data over HTTP instead of directly from a filesystem then you could use the XMLHttpRequest object (or, in newer browsers, fetch) which Angular abstracts through $http .

If you are using Firefox, then you can use that approach to read local files which are in the same directory (or a subdirectory of it) as the HTML document. Other browsers have stricter security rules.

If you allowed the user to select the file (via a <input type="file"> ) then you could use the FileReader API.

$http.get("timeZones.json")
  .then(function onSuccess(response) {
    // Handle success
    var data = response.data;
    var status = response.status;
    var statusText = response.statusText;
    var headers = response.headers;
    var config = response.config;         
    //...
    vm.timeZones = data;
  })
  .catch(function onError(response) {
    // Handle error
    var data = response.data;
    var status = response.status;
    var statusText = response.statusText;
    var headers = response.headers;
    var config = response.config;
    //...
  });

For more infomation, see AngularJS $http Service API Reference .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM