12

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?

allez l'OM
  • 547
  • 4
  • 13
  • 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 Oct 19 '19 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 Oct 27 '19 at 11:18
  • Becasue https://github.com/whatwg/fetch/issues/104 – Bergi Oct 27 '19 at 13:05

2 Answers2

9

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))
    // ...
Emissary
  • 9,954
  • 8
  • 54
  • 65
-5

You could do:

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

Hope it helps ;)

Janus
  • 645
  • 2
  • 7
  • 18
  • The OP is trying to parse the JSON in a specific way, – Titus Oct 19 '19 at 11:44
  • 2
    The question asks how to use a _reviver_, the [optional second argument to `JSON.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#using_the_reviver_parameter), when using `response.json()`. Using `response.json()` **won't work** as it does't take a reviver argument. – Martijn Pieters Jan 27 '21 at 20:18