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?

5
  • 6
    Use a try-catch block around it. Commented Jul 4, 2017 at 11:53
  • And implement input validation. Commented Jul 4, 2017 at 11:54
  • 1
    stackoverflow.com/questions/4467044/… Commented Jul 4, 2017 at 11:55
  • @Sirko is right, and then you can right a help function that will return null if the JSON input is not valid.. Commented Jul 4, 2017 at 11:55
  • user input into a text box? Commented Jul 4, 2017 at 11:56

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.