1

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

3

3 Answers 3

3

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
}
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

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?
@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?
0

You can try it a way as below:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.