Arun Mohan
Arun Mohan

Reputation: 978

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?.

Upvotes: 1

Views: 7666

Answers (3)

Sanjay Nishad
Sanjay Nishad

Reputation: 1625

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
}

Upvotes: 3

Anjan Kant
Anjan Kant

Reputation: 4316

You can try it a way as below:

var age = 34;
ar obj = { name: "arun", age }
console.log(JSON.stringify(obj));

Upvotes: 0

LetterEh
LetterEh

Reputation: 26706

You aren't going to get an error from JSON.stringify, here.

As soon as you try to make this object, you should get an error.

var obj = {
  name: "Arun"  // you're missing a comma
  age //this is valid, as long as `age` exists as a variable above this point, in new browsers
};

In all browsers, as soon as you run this part of the script, it's going to throw a SyntaxError, because you're missing the comma.

If you added that comma back in, and age did exist above:

var age = 32;
var obj = {
  name: "Arun",
  age
};

This would now work fine in brand-new browsers, but would again throw a SyntaxError in older browsers.

The legacy-compatible version of that object would look like:

var age = 32;
var obj = {
  name: "Arun",
  age: age
};

The problem you're having doesn't seem to be that .stringify would be breaking. Based on the object you provided, your statement is broken, period.

Upvotes: 1

Related Questions