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

1.4k views Asked by At

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?

2

There are 2 answers

0
Emissary On

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))
    // ...
2
Janus On

You could do:

fetch(url)
.then((response) => {return response.json()})
.then((json) => {console.log(json)});

Hope it helps ;)