Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.stringify returns "[object Object]" instead of the contents of the object

Here I'm creating a JavaScript object and converting it to a JSON string, but JSON.stringify returns "[object Object]" in this case, instead of displaying the contents of the object. How can I work around this problem, so that the JSON string actually contains the contents of the object?

var theObject = {name:{firstName:"Mark", lastName:"Bob"}};
alert(JSON.stringify(theObject.toString())); //this alerts "[object Object]"
like image 420
Anderson Green Avatar asked May 11 '13 03:05

Anderson Green


People also ask

Does JSON Stringify change the object?

JSON. stringify() takes a JavaScript object and then transforms it into a JSON string. JSON. parse() takes a JSON string and then transforms it into a JavaScript object.

What does JSON Stringify do to an object?

The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

How do you Stringify an object object?

Stringify a JavaScript Objectstringify() to convert it into a string. const myJSON = JSON. stringify(obj); The result will be a string following the JSON notation.

Why JSON Stringify does not work on array?

The JSON array data type cannot have named keys on an array. When you pass a JavaScript array to JSON. stringify the named properties will be ignored. If you want named properties, use an Object, not an Array.


3 Answers

Use alert(JSON.stringify(theObject));

like image 169
Arbel Avatar answered Sep 23 '22 17:09

Arbel


theObject.toString()

The .toString() method is culprit. Remove it; and the fiddle shall work: http://jsfiddle.net/XX2sB/1/

like image 31
hjpotter92 Avatar answered Sep 23 '22 17:09

hjpotter92


JSON.stringify returns "[object Object]" in this case

That is because you are calling toString() on the object before serializing it:

JSON.stringify(theObject.toString()) /* <-- here */

Remove the toString() call and it should work fine:

alert( JSON.stringify( theObject ) );
like image 41
Kevin Boucher Avatar answered Sep 21 '22 17:09

Kevin Boucher