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
JSON. parse() is used to convert String to Object. JSON. stringify() is used to convert Object to String.
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.
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.
JSON. stringify() is the opposite of JSON. parse(), which converts JSON into Javascript objects.
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.
'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.
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