46

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]"
Anderson Green
  • 27,734
  • 61
  • 179
  • 311
  • Alerts don't show objects, only strings, you should be using the console for that. And converting an object to a string does the same, you end up with [object Object], as that is the string representation of an object. – adeneo May 11 '13 at 03:43
  • 4
    `theObject.toString()` = `"[object Object]"` – Nirvana Tikku May 11 '13 at 03:59
  • 1
    Ever wondered why [object Object] ? Have a look at this answer : http://stackoverflow.com/a/25419538/3001704 – kchetan Nov 15 '16 at 09:33

4 Answers4

53

Use alert(JSON.stringify(theObject));

Arbel
  • 29,356
  • 2
  • 26
  • 29
6
theObject.toString()

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

hjpotter92
  • 75,209
  • 33
  • 136
  • 171
4

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 ) );
Kevin Boucher
  • 15,718
  • 3
  • 43
  • 54
1

Use

var theObject = {name:{firstName:"Mark", lastName:"Bob"}};
alert(JSON.stringify(theObject));
Tamil Selvan C
  • 19,232
  • 12
  • 49
  • 68