简体   繁体   English

JSON.stringify返回“[object Object]”而不是对象的内容

[英]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. 这里我创建一个JavaScript对象并将其转换为JSON字符串 ,但在这种情况下JSON.stringify返回"[object Object]" ,而不是显示对象的内容。 How can I work around this problem, so that the JSON string actually contains the contents of the object? 我该如何解决这个问题,以便JSON字符串实际上包含对象的内容?

var theObject = {name:{firstName:"Mark", lastName:"Bob"}};
alert(JSON.stringify(theObject.toString())); //this alerts "[object Object]"

使用alert(JSON.stringify(theObject));

theObject.toString()

The .toString() method is culprit. .toString()方法是罪魁祸首。 Remove it; 去掉它; and the fiddle shall work: http://jsfiddle.net/XX2sB/1/ 小提琴应该起作用: http//jsfiddle.net/XX2sB/1/

JSON.stringify returns "[object Object]" in this case 在这种情况下,JSON.stringify返回“[object Object]”

That is because you are calling toString() on the object before serializing it: 那是因为在序列化之前你在对象上调用toString()

JSON.stringify(theObject.toString()) /* <-- here */

Remove the toString() call and it should work fine: 删除toString()调用,它应该工作正常:

alert( JSON.stringify( theObject ) );

Use 使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM