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 extrathen
call asJSON.parse
is synchronous, so you can just do it at the beginning of the nextthen
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
2 Answers
Reset to default 11Your 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
版权声明:本文标题:javascript - how to use reviver function with fetch.response.json() - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744550080a2612130.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论