Check valid JSON with jQuery
If you receive json data from an external service, you should make sure if the data is a proper formed json. With this code you can quickly test the data.
This is just a quick hint for the validation of JSON (JavaScript Object Notation). If you do AJAX requests, you probably use JSON to transmit your data objects. But if the response is not valid, your code of your callback function presumably do not work as expected.
That can be a risk, because the user looks for a visual feedback. The error is only printed in the console.
$.ajax(
{
url: 'example.com',
success: function (response) {
var encodedJson;
try{
//try to parse JSON
encodedJson = $.parseJSON(response);
//use JSON
encodedJson.name
}catch(error){
//handle error -> visual feedback for user
}
}
}
);
Please comment below, if you have any questions.
Credits:
- Post photo by Irvan Smith on Unsplash