Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

206
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda