Javascript is not accepting JSON data as variable

Viewed 41

I am trying to connect to an API to display some data on my website.

I've already defined Http as new XMLHttpRequest();, and url as the API endpoint.

Here's the code:

Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
      var api = JSON.stringify(Http.responseText)
      document.getElementById("stat").innerHTML = "Powering over " + api.total_bandwidth.TB + "TB of private internet traffic"
}

However, when I run the code, I get the following error:

Uncaught TypeError: api.total_bandwidth is undefined

What is wrong here? Is Http.responseText already an Object? Did I define the API wrong?

This is the response of api:

{"total_bandwidth": {"GB": 110842.05, "TB": 108.24, "PB": 0.11}}
1 Answers

You're stringifying the object (response), then trying to get "TB" from a string.

Try parsing api then getting the properties from it:

Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
    var api = JSON.stringify(Http.responseText);
    var apiJson = JSON.parse(api);
    document.getElementById("stat").innerHTML = "Powering over " + apiJson.total_bandwidth.TB + "TB of private internet traffic";
};

Edit: Turns out that "JSON.stringify" was actually a mistake.

I think you meant to use JSON.parse rather than JSON.stringify... - Robin Zigmond

I think you meant JSON.parse (to PARSE the response text) instead of JSON.stringify:

Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
      var api = JSON.parse(Http.responseText);
      document.getElementById("stat").innerHTML = "Powering over " + api.total_bandwidth.TB + "TB of private internet traffic"
}

Learn more about JSON.parse at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Related