Anderson Green
Anderson Green

Reputation: 31850

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]"

Upvotes: 57

Views: 163330

Answers (4)

Arbel
Arbel

Reputation: 30999

Use JSON.stringify(theObject);

Upvotes: 68

Kevin Boucher
Kevin Boucher

Reputation: 16705

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 ) );

Upvotes: 7

Tamil Selvan C
Tamil Selvan C

Reputation: 20229

Use

var theObject = {name:{firstName:"Mark", lastName:"Bob"}};
alert(JSON.stringify(theObject));

Upvotes: 2

hjpotter92
hjpotter92

Reputation: 80657

theObject.toString()

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

Upvotes: 6

Related Questions