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

195
Vistas
Why I cant JSON.parse a string from an API (Error msg: Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>))

I am trying to fetch a joke using XMLHTTPRequest from a random joke generating API as practice.

Here is my code

    <script>
    const xhr = new XMLHttpRequest();

    xhr.open('get', 'https://icanhazdadjoke.com/', true);
    xhr.setRequestHeader('Accept', 'application/json')
        const joke = JSON.parse(xhr.response)

    xhr.onload = function () {console.log(xhr.responseText)}
    xhr.send();

</script>

and the error message i get is: Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse ()

Funny thing is if I do JSON.parse(xhr.response) and save it to a variable, it works perfectly fine. What am I doing wrong in my script?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You're trying to parse the response before receiving the response. (AJAX is asynchronous.) You need to handle the response in the onload handler, just like you already are when you try to log it to the console:

const xhr = new XMLHttpRequest();

xhr.open('get', 'https://icanhazdadjoke.com/', true);
xhr.setRequestHeader('Accept', 'application/json');

xhr.onload = function () {
  const joke = JSON.parse(xhr.response);
  console.log(joke);
}
xhr.send();

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