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]"
JSON. stringify() takes a JavaScript object and then transforms it into a JSON string. JSON. parse() takes a JSON string and then transforms it into a JavaScript object.
The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
Stringify a JavaScript Objectstringify() to convert it into a string. const myJSON = JSON. stringify(obj); The result will be a string following the JSON notation.
The JSON array data type cannot have named keys on an array. When you pass a JavaScript array to JSON. stringify the named properties will be ignored. If you want named properties, use an Object, not an Array.
Use alert(JSON.stringify(theObject));
theObject.toString()
The .toString()
method is culprit. Remove it; and the fiddle shall work: http://jsfiddle.net/XX2sB/1/
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 ) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With