Home > Blockchain >  How to convert response.text() to JSON with react
How to convert response.text() to JSON with react

Time:02-19

In the following

  const fetchData = async () => {
    try {
      const response = await fetch("http://front-assignment.codeit.team/");
      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.

This is what my preview looks like for the endpoint

enter image description here

CodePudding user response:

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)

CodePudding user response:

Try this JSON.parse(responseData)

const fetchData = async () => {
try {
  const response = await fetch("http://front-assignment.codeit.team/");
  const data = await response.text()
  console.log('data', JSON.parse(data));
 } catch (error) {
  console.error(error)
 } finally {
  setLoading(false)
 }
}

Other solution:

fetch('targetedURL')
.then(response => response.json())
.then(data => console.log(data));
  • Related