Converting an object to a string
Use JSON.stringify(obj)
to convert a Javascript object into a JSON string.
JSON.stringify()
method doesn't convert object's function
instances and Symbol
types.
To handle complex objects, you may need custom string conversion or a library that can handle complex serialization.
Again, JSON.stringify()
"happily converting" objects to strings since 1999.
Thriving in the legacy world (pre-ES5 browsers)
If you're somehow stuck in the early 2000s and need to support legacy browsers, here’s an alternative for JSON.stringify:
Douglas Crockford’s JSON-js. No song and dance required, it just works.
Handy tools to tame objects
The String()
function
The String()
function is the simpler, less fussy cousin of JSON.stringify()
. It turns an object into a string but leaves out details about properties.
Remember, it's apparent simplicity might not always be a boon.
The loquacious console.log
For peeking into an object's property values, just separate the object and the string with a comma when using console.log
.
Why invite complexity by concatenating string with an object? Some JavaScript complexities can be more tangled than headphones in the pocket.
DIY: Building your own serializer
Serious business needs serious tools. Craft your custom serializer iterating over Object.entries(obj)
.
Beware—all that glitters is not gold
Tricky non-serializable properties
JSON.stringify()
might miss out unserializable properties such as functions
, undefined
, or circular references
. It’s not playing hide and seek, it’s just how JavaScript designed it.
The elusive toSource()
Remember to brush up your French; toSource()
is like the French language memory from high school—useful but hardly supported everywhere.
In the realm of compatibility
Before venturing with Object.entries
or other ES6+ methods, better check for browser compatibility. Polyfills can be your armor in the older browser battle.
Alert—it's testing time
To quickly visualize an object, alert(JSON.stringify(obj))
is a handy trick. Yes, it can get annoying, but then so was your first "Hello, World!" for people nearby.
Was this article helpful?