0

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.

Community
  • 1
  • 1
Legionar
  • 7,472
  • 2
  • 41
  • 70
  • 3
    I think you are doing it right. check this answer http://stackoverflow.com/questions/3710204/how-to-check-if-a-string-is-a-valid-json-string-in-javascript-without-using-try – Anoop Joshi P Apr 26 '16 at 13:40
  • 2
    The accepted answer there is incorrect, but this answer (with most votes) should be correct, yes? http://stackoverflow.com/a/3710226/1631551 – Legionar Apr 26 '16 at 13:42
  • That's what I would do. Here's another similar - http://stackoverflow.com/a/8431765/1161948 – ThisClark Apr 26 '16 at 13:43
  • 1
    @Legionar you must go for the most upvoted answer . – Anoop Joshi P Apr 26 '16 at 13:44
  • Umm, I think you went overboard on your `try-catches`. You don't really need to do it on `console.log();` statements. – dokgu Apr 26 '16 at 13:47
  • @PatrickGregorio Yes, I know that; but its only piece of my code, in product version of my code, there I need to have `try-catches` and without `console.log()`. – Legionar Apr 26 '16 at 13:48

1 Answers1

2

How about JSON.parse()?

$.post(
    'some_url.php',
    some_params,
    function(data) {
            try {
                console.log(JSON.parse(data));
            }
            catch(err) {
                console.log('error occured');
            }
    }
);
Diego Polido Santana
  • 1,425
  • 11
  • 19