23

I have been working with fetch API and Promises recently and I came across .json() . Oftentimes .json() returns the same output as JSON.parse. I googled the question and the results pointed in other directions.

Example with XHR and JSON.parse:

$('#xhr').click(function(){
  var XHR = new XMLHttpRequest();

  XHR.onreadystatechange = function(){
    if (XHR.status == 200 && XHR.readyState == 4) {
      $('#quote').text(JSON.parse(XHR.responseText)[0]);
    }
  };

  XHR.open("GET", url);
  XHR.send();
});

Example with Fetch API:

$('#fetch').click(function(){
  fetch(url)
  .then(function(res){
    return res.json();
  })
  .then(function(quote){
    $('#quote').text(quote);
  })
  .catch(function(err){
    handleError(err);
  });
});

Could someone please explain the difference between these seemingly similar concepts ? Thanks

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Isfaaq
  • 415
  • 1
  • 4
  • 15

4 Answers4

43

Body.json() is asynchronous and returns a Promise object that resolves to a JavaScript object. JSON.parse() is synchronous can parse a string and change the resulting returned JavaScript object.

guest271314
  • 1
  • 15
  • 104
  • 177
  • Thanks for your reply. :) – Isfaaq Jan 17 '18 at 07:15
  • Body.json() returns a promise - but i see some examples where data = Body.json() is used so the data is accessed directly- apparently without unwrapping the promise - but in other examples i see the promise used via .then(data) and the data is accessed off of the promise. Why does the first example work? Thanks. – john blair Jun 29 '20 at 08:01
5

'AJAX' works with 'callbacks'; 'fetch' works with 'promises'.

Use JSON.parse() to parse the response for AJAX. Use json() to parse the response for fetch.

Andreycw
  • 63
  • 1
  • 5
3

In my view both res.json and JSON.parse do the same functioning. Preference to res.json is given because of it's syntax. Sharing the example for better understanding...

 this.service.userFunction() //calling service
.then((res) => {
 this.userdetails = JSON.parse(res._body); //use this
 this.userdetails = res.json(); // or use this syntax any one
 )}
.catch()

Using any of one them will provide the the complete response body and understanding of their functionality.

Yogesh Aggarwal
  • 994
  • 7
  • 9
  • res.json() returns a promise, so after returning that, you would need to chain an additional then(data){ this.userdetails = data } – kennsorr Dec 23 '20 at 19:31
2

The json() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON. The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.

Use JSON.parse() to parse the response for AJAX. Use json() to parse the response for fetch.

adi1ya
  • 404
  • 1
  • 7
  • 10