admin管理员组

文章数量:1386813

There is a "reviver" function that es 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?

There is a "reviver" function that es 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?

Share Improve this question asked Oct 19, 2019 at 11:24 allez l'OMallez l'OM 5775 silver badges14 bronze badges 3
  • 2 No need for that new Promise wrapper. And of course you don't need an extra then call as JSON.parse is synchronous, so you can just do it at the beginning of the next then callback. – Bergi Commented Oct 19, 2019 at 11:27
  • @Bergi : I do agree with you about the wrapper. But the reviver allows to removing useless properties, resulting in a much lighter object (if huge json files). If the reviver exists with JSON.parse, why not in fetch.response.json? – allez l'OM Commented Oct 27, 2019 at 11:18
  • Becasue github./whatwg/fetch/issues/104 – Bergi Commented Oct 27, 2019 at 13:05
Add a ment  | 

2 Answers 2

Reset to default 11

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))
    // ...

You could do:

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

Hope it helps ;)

本文标签: javascripthow to use reviver function with fetchresponsejson()Stack Overflow