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?
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.
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.
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 .
A reviver function can be used to filter or transform the value being parsed.
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))
// ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With