59

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]"
3
  • 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. Commented May 11, 2013 at 3:43
  • 4
    theObject.toString() = "[object Object]" Commented May 11, 2013 at 3:59
  • 1
    Ever wondered why [object Object] ? Have a look at this answer : stackoverflow.com/a/25419538/3001704 Commented Nov 15, 2016 at 9:33

4 Answers 4

69

Use JSON.stringify(theObject);

Sign up to request clarification or add additional context in comments.

2 Comments

how to get name from json string
@oxygen Per OP example above, Use: console.log(JSON.stringify(theObject.name.firstName.toString())); // output: "Mark"
8

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

Comments

7
theObject.toString()

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

Comments

3

Use

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

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.