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

613
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 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