I found couple similar answers on SO, but none of them are enough. I'm calling ajax with $.post()
and expcecting json-string returned.
Many things can occur (incorrect json format, server side error, connection lost etc.) and I'm trying to test, if the returned string is json
valid.
I checked this answer, but it is using eval
, which is not safe.
Here is my code, which I wrote by now:
$.post(
'some_url.php',
some_params,
function(data) {
var is_JSON = true;
try {
data = $.parseJSON(data);
}
catch(err) {
is_JSON = false;
}
if (is_JSON && (data !== null)) {
console.log('correct json format');
if (data.result === 'OK') {
console.log('result: OK');
}
else if (data.result === 'ERR') {
console.log('result: ERR');
}
}
else {
try {
console.log('incorrect json format');
}
catch(err) {
console.log('error occured');
}
}
}
);
How can I simply (and just enough) check, if returned string is in correct json format? Thanks.