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.

6
  • 3
    I think you are doing it right. check this answer stackoverflow.com/questions/3710204/… Commented Apr 26, 2016 at 13:40
  • 2
    The accepted answer there is incorrect, but this answer (with most votes) should be correct, yes? stackoverflow.com/a/3710226/1631551 Commented Apr 26, 2016 at 13:42
  • That's what I would do. Here's another similar - stackoverflow.com/a/8431765/1161948 Commented Apr 26, 2016 at 13:43
  • 1
    @Legionar you must go for the most upvoted answer . Commented Apr 26, 2016 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. Commented Apr 26, 2016 at 13:47

1 Answer 1

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');
            }
    }
);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.