Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is `Body.json()` faster than `JSON.parse(responseText)` for JSON received from `fetch`?

Is Body.json() faster than JSON.parse(responseText) for JSON received from fetch?

Theoretically Body.json() can start decoding JSON as soon as it receives the first bytes from the ReadableStream from fetch. Is this how it works? Or does it wait until all bytes are received?

const response = await fetch(url);
const json = await response.json();
const response = await fetch(url);
const text = await response.text();
const json = JSON.parse(text);

So, is there a difference between these versions of the code?

like image 236
KeyKi Avatar asked Mar 28 '20 14:03

KeyKi


People also ask

What is the difference between JSON parse () and JSON ()?

The difference is: json() is asynchronous and returns a Promise object that resolves to a JavaScript object. JSON. parse() is synchronous can parse a string to (a) JavaScript object(s).

Which method helps to extract the JSON body content from the response?

We can extract the whole JSON as a string in Rest Assured. This is achieved with the help of the extract method. It shall extract the whole response as a string using the asString method.

What is response JSON () in fetch?

Response.json()The json() method of the Response interface takes a Response stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON .

How do I get JSON from fetch response?

To get JSON from the server using the Fetch API, you need to use the fetch() method. We need to use an additional call to the response. json() method to get the response body. The "Accept: application/json" header accepts the type of data the client wants to receive in the response.


1 Answers

You are right that the body gets consumed while fetching (and that the body is a stream), but per specs, when the browser is to consume the body, it has to read all bytes from this stream with a stream reader before it can "[r]eturn the result of transforming promise by a fulfillment handler that returns the result of the package data algorithm".

This means that before Body.json() can even call its first step utf-8-decode, the full body must already have been read as an Uint8Array, and the same applies to all package data types.

Then we can conclude that

fetch( url )
  .then( body => body.json() );

is actually syntactic sugar for

fetch( url )
  .then( body => body.arrayBuffer() )
  .then( bytes => new TextDecoder().decode( bytes ) )
  .then( text => JSON.parse( text ) );

and that

fetch( url )
  .then( body => body.text() );

is itself syntactic sugar for

fetch( url )
  .then( body => body.arrayBuffer() )
  .then( bytes => new TextDecoder().decode( bytes ) )

And thus if you add yourself the .then( text => JSON.parse( text ) ), you actually have exactly the same operations being performed.

like image 129
Kaiido Avatar answered Oct 14 '22 02:10

Kaiido