Member-only story
Beginner Goodies: Convert a JavaScript Object to JSON String
Almost every high level language has a toString method for primitive data types like Integer, Float, and maybe Boolean. If you learned another programming language before trying JavaScript or Node.js, you’ll probably get frustrated every time your intuition is wrong. There are some caveats with JS toString and objects. I’ll show you some examples of basic JavaScript JSON encoding and decoding.
JavaScript Object to String
JavaScript too has a toString method on several of its primitives, however the JS object toString will resolve a confusing output for beginners. You’ll likely find this out after you’ve already executed the .toString() on an instance of an object. Suddenly you see this ugly result, that doesn’t even throw you an error.
Confusing, right? This is completely normal. Welcome to JavaScript. If you want to convert your JS object to a JSON string, you’ll need to use the stringify method on JavaScript’s native JSON object. This will encode the object to a string in both the web browser and Node.js.










