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.

  • 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 – shyam Nov 14 '13 at 12:54
  • You trying to parse Text as JSON, this will fail! – Fals Nov 14 '13 at 12:55
  • @shyam this is the whole point, resp can be text or JSOn, I need to differentiate between too. –  Nov 14 '13 at 12:55
  • 1
    here's a json checking regex you can make use of, http://stackoverflow.com/questions/3710204/how-to-check-if-a-string-is-a-valid-json-string-in-javascript-without-using-try – ETAN Nov 14 '13 at 12:55
  • @Fals well, I understood that, but how do I differentiate between this two on resp? –  Nov 14 '13 at 12:55
  • "Passing in a malformed JSON string results in a JavaScript exception being thrown. " – Anthony Nov 14 '13 at 12:56
  • Are you getting either a text or JSON response _from the same URL_? That seems wrong somehow. If you're using the same ajax routine for different URLs, I suggest either making a new ajax routine, or calibrating your existing one to cater for different `dataTypes` which you're not doing by the looks of things. – Andy Nov 14 '13 at 13:05

1 Answers1

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;
    }
benzonico
  • 10,635
  • 5
  • 42
  • 50