Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to process JSON error message

I am a complete beginner with JavaScript and jQuery.

When I query my API I will normally get JSON like this:

{
  "soc": 9271,
  "series": [
    {
      "year": 2013,
      "estpay": 370
    },
    {
      "year": 2012,
      "estpay": 430
    }
  ]
}

However if my query is invalid I will get JSON like this:

{
  "error": "Some message here . . . .."
}

So my question is - what is the syntax to detect the error message and then set up an IF / ELSE type of response? i.e. If error message do this.. If no error message do something else.

like image 476
Bizzy Avatar asked Nov 08 '22 17:11

Bizzy


1 Answers

You can try using an implemented JSON tool which has this methods built inside.

secondly you can try and use this:

if (response){
    try{
        a=JSON.parse(response);
    }catch(e){
        alert(e); //error in the above string(in this case,yes)!
    }
}

Good luck!

like image 115
Ido Michael Avatar answered Nov 14 '22 22:11

Ido Michael