javascriptjson

How to get the error message for JSON stringify?


Suppose I have an object like this

var obj = {
"name": "arun"
age
}

When I try this, JSON.stringify(obj), I will be recieving an error since the obj is not proper. I want to capture the error shown in the console and show it in the UI.

Is there any callback functionality for the stringify function,so that I can do the above?.


Solution

  • First thing, there is a syntax error, after "name": "arun" you need to add ,

    we can't get syntax error programmatically. after correcting this syntax error, you can check like this

    try{
    
       var obj = {
         "name": "arun",
         age
       }
    
     } catch(e){
       console.log(e);// you can get error here
    }