0

I want to differentiate between server response, json based or pure text. So in my ajax call I've:

success: function(resp) {
    //
    json = $.parseJSON(resp);
    if (typeof json == "object") {
        console.dir(json);
    } else {
        console.dir(resp);
    }
    //
}

Problem is, it breaks on Parse line, so I can never reach line where I check typeof...

Uncaught SyntaxError: Unexpected token

What am I doing wrong?

p.s. resp is sometimes json, sometimes pure text.

7
  • 1
    How does the response look like? If the response is not JSON (ie. key names quoted with ") then don't call parseJSON on it Commented Nov 14, 2013 at 12:54
  • You trying to parse Text as JSON, this will fail! Commented Nov 14, 2013 at 12:55
  • @shyam this is the whole point, resp can be text or JSOn, I need to differentiate between too. Commented Nov 14, 2013 at 12:55
  • 1
    here's a json checking regex you can make use of, stackoverflow.com/questions/3710204/… Commented Nov 14, 2013 at 12:55
  • @Fals well, I understood that, but how do I differentiate between this two on resp? Commented Nov 14, 2013 at 12:55

1 Answer 1

2

If you are not receiving Json then you cannot parse it.

You shoud try/catch the error :

 var response;
 try{
       response=$.parseJSON(resp);
       //if you pass this without error your json is valid json
       }catch(err){
       //handle here the resp as plain text.
       response=resp;
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.