Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use reviver function with fetch.response.json()

There is a "reviver" function that comes with JSON.parse (eg: "JSON.parse using reviver function").

How can I use this "reviver" with response.json? for instance:

fetch(url)
.then(a => a.json({reviver}))    // unfortunately not working
.then(...)

I have a workaround:

fetch(url)
.then(a => a.text())
.then(b => new Promise((resolve) => resolve(JSON.parse(b, reviver))))
.then()

but it uses one more step, which seems useless. Any better idea?

like image 452
allez l'OM Avatar asked Oct 19 '19 11:10

allez l'OM


People also ask

How do I get JSON from fetch response?

To get JSON from the server using the Fetch API, you can use the response. json() method. The response. json() method reads the data returned by the server and returns a promise that resolves with a JSON object.

What is Reviver in JSON parse?

The purpose of this function is to modify the result before returning. In simple terms this reviver function can be thought of as a filter function. All parsed values are passed through this reviver function in key-value pair before being returned. JSON.

What is response JSON () in fetch?

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 .

What is reviver function in JavaScript?

A reviver function can be used to filter or transform the value being parsed.


1 Answers

Your workaround is basically the best option but as mentioned, the extra promise is unnecessary.

fetch(url)
    .then(response => response.text())
    .then(text => JSON.parse(text, reviver))
    // ...
like image 90
Emissary Avatar answered Nov 01 '22 09:11

Emissary