Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

606
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!