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

試著忘記壹切 提交于 2019-11-30 00:13:56

问题


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

回答1:


Use alert(JSON.stringify(theObject));




回答2:


theObject.toString()

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




回答3:


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



回答4:


Use

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


来源:https://stackoverflow.com/questions/16493498/json-stringify-returns-object-object-instead-of-the-contents-of-the-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!