0

I have a string that I obtain via a user, so it is not guaranteed to be a correct JSON string format.

This problem may cause the rest of the js code to be stop.

Consider the following example:

var a='==wrong string===';
var b=JSON.parse(a);
alert(1); //will not implemented

How to avoid this problem?

Amiga500
  • 5,874
  • 10
  • 64
  • 117
Sherif Eldeeb
  • 199
  • 2
  • 11

1 Answers1

1

You can use try catch block:

var a='==wrong string===';
try{
  var b=JSON.parse(a);
 }catch(e){
  console.log(e.message); /*use e.message to get the exact error */
 }
alert(1)
Shubham
  • 1,755
  • 3
  • 17
  • 33
Carlos Franco
  • 210
  • 2
  • 9