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,330
  • 9
  • 56
  • 103
Sherif Eldeeb
  • 179
  • 2
  • 10

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,655
  • 3
  • 14
  • 31
Carlos Franco
  • 210
  • 2
  • 9