Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

148
Vistas
Javascript is not accepting JSON data as variable

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}}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda