Explain Codes LogoExplain Codes Logo

Converting an object to a string

javascript
object-serialization
json-stringify
browser-compatibility
Alex KataevbyAlex Kataev·Dec 30, 2024
TLDR

Use JSON.stringify(obj) to convert a Javascript object into a JSON string.

const obj = { species: "Dog", name: "Otis" }; console.log(JSON.stringify(obj)); // {"species":"Dog","name":"Otis"}

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.

const obj = { species: "Dog", name: "Otis" }; console.log(String(obj)); // [object Object]

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.

console.log("Our pet: ", obj); // Logs: Our pet: { species: 'Dog', name: 'Otis' }

DIY: Building your own serializer

Serious business needs serious tools. Craft your custom serializer iterating over Object.entries(obj).

const mySerializer = Object.entries(obj).map(([key, val]) => `${key}: ${val}`).join(', '); console.log(mySerializer); // species: Dog, name: Otis

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.