Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.parse() Vs. .json()

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

like image 986
Isfaaq Avatar asked Jan 17 '18 07:01

Isfaaq


People also ask

What is difference between JSON parse and JSON Stringify?

JSON. parse() is used to convert String to Object. JSON. stringify() is used to convert Object to String.

What is JSON parse?

JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON. parse() , as the Javascript standard specifies.

Do I need to use JSON parse?

JSON as a string json or profiles. json above, that file actually contains text in the form of a JSON object or array, which happens to look like JavaScript. Just like with text files, if you want to use JSON in your project, you'll need to parse or change it into something your programming language can understand.

Is JSON parse the opposite of JSON Stringify?

JSON. stringify() is the opposite of JSON. parse(), which converts JSON into Javascript objects.


2 Answers

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.

like image 106
guest271314 Avatar answered Oct 19 '22 20:10

guest271314


'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.

like image 5
user2949477 Avatar answered Oct 19 '22 21:10

user2949477