53

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
  • 30,230
  • 67
  • 195
  • 328
  • 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

60

Use JSON.stringify(theObject);

Arbel
  • 30,599
  • 2
  • 28
  • 29
6
theObject.toString()

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

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
6

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
  • 16,426
  • 3
  • 48
  • 55
2

Use

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