0

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

Arun Mohan
  • 898
  • 3
  • 18
  • 37

3 Answers3

2

First think 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
}
Sanjay Nishad
  • 1,537
  • 14
  • 26
1

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.

Norguard
  • 26,167
  • 5
  • 41
  • 49
  • I know the object is faulty, I want to validate that faulty json object and to tell there is an error,at line 3 of the object. Is there any way to do that? – Arun Mohan Feb 25 '16 at 07:21
  • @ArunMohan It's not a JSON object, if you are declaring it in JavaScript. `var obj = { ];` is not JSON, it's JS. And it will explode before you ever try to put it inside of `stringify`. If you are downloading it as JSON text, that's a very different thing, and then you wouldn't use `stringify`, you'd use `parse` to turn the string into a JS object. Which do you mean? – Norguard Feb 25 '16 at 07:59
0

You can try it a way as below:

var age = 34;
ar obj = { name: "arun", age }
console.log(JSON.stringify(obj));
Anjan Kant
  • 4,090
  • 41
  • 39