1

After converting a response stream into JSON, are the two exactly the same?

const responseA = fetch(endpointReturnsJson)
const textA = await responseA.text()

In a parallel universe...

const responseA = fetch(endpointReturnsJson)
const json = await responseA.json()
const textB = JSON.stringify(json)

I understand that textB will likely include serialization of characters such as {\\ Is there anything else?

2
  • 3
    First of all you are missing await in front of both fetch and response.json/response.text. And assuming the response was valid JSON in the first place: JSON.parse(await response.text()) should give the same result as await response.json(), but not necessarily the other way round because for example the whitespace may be different. Commented Aug 19, 2020 at 23:09
  • Thank you! Haha incorrectly contrived Commented Aug 20, 2020 at 14:54

1 Answer 1

3

It all depends on what stuff is.

If you use response.json(), you are assuming that the incoming stream was JSON-encoded. The method will take the stream's body's text and parse it.

When the data is not in JSON format, then access it with response.text() and process it accordingly.

Read more: https://developer.mozilla.org/en-US/docs/Web/API/Response

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.