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

617
Visualizações
How to convert response.text() to JSON with react

In the following

  const fetchData = async () => {
    try {
      const response = await fetch("faulty-endpoint");
      const data = await response.text()
      console.log('data', data)
    } catch (error) {
      console.error(error)
    } finally {
      setLoading(false)
    }
  }

How do I turn the response.text() data back to json? I can't do

const data = await response.json()

Because then I console.log nothing. I want it to be JSON format so I can save it into a useState array that I can map across.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Because of that trailing comma, you can remove it first, then use JSON.parse:

let text = await response.text();

// if trailing comma present, remove last character by slicing it off
// -1 in slice is the same as text.length - 1
if (text.endsWith(",")) text = text.slice(0, -1);

const data = JSON.parse(text);

This isn't the best or cleanest solution however; ideally the API should return valid JSON...

about 4 years ago · Juan Pablo Isaza Relatório

0

Here's a working proof-of-concept implementation of youdateme's answer.

I'm faking the request here to avoid CORS issues and such, but the response is copied from the endpoint in your question.

(Note: I had to re-escape the quotes around \"Hello World\" in the last record in the exported template string.)

It does what youdateme suggested and it works.

const fetchData = async () => {
  try {
    const response = await fakeRequest();
    const data = JSON.parse(response.replace(/,$/, ""));
    setData(data);
  } catch (error) {
    console.error(error);
  }
};

fetchData();

If this solves your problem you should accept youdateme's answer.

about 4 years ago · Juan Pablo Isaza Relatório

0

JSON and a JavaScript object look similar, but they're different. JSON is only a string that's formatted like a JavaScript object. See: Working with JSON - MDN

To map across, you need it to be a JavaScript object, not JSON.

Use JSON.parse(yourResponse) to parse a JSON string into a JavaScript object (or array, etc.). See: JSON.parse from MDN

To convert a JavaScript object into a JSON string, you may use JSON.stringify(yourObject)

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