Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
103
rated 0 times [  107] [ 4]  / answers: 1 / hits: 16811  / 6 Years ago, wed, january 17, 2018, 12:00:00

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


More From » json

 Answers
9

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.


[#55439] Saturday, January 13, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kyla

Total Points: 77
Total Questions: 108
Total Answers: 111

Location: Grenada
Member since Mon, May 8, 2023
1 Year ago
;