简体   繁体   English

如何使用 reviver function 与 fetch.response.json()

[英]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" ). JSON.parse 附带一个“reviver” function (例如: “JSON.parse using reviver function” )。

How can I use this "reviver" with response.json ?如何将这个“复兴者”与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?有更好的主意吗?

Your workaround is basically the best option but as mentioned, the extra promise is unnecessary.您的解决方法基本上是最好的选择,但如前所述,额外的 promise 是不必要的。

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;)希望能帮助到你;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM