Convert an Object to JSON String using JavaScript

avatar

Borislav Hadzhiev

Wed Nov 03 20212 min read

Convert an Object to JSON String using JavaScript #

Use the JSON.stringify() method to convert an object to a JSON string, e.g. const json = JSON.stringify(obj). The method takes a value, converts it to a JSON string and returns the result.

index.js
const obj = { name: 'Tom', country: 'Chile', }; // โœ… Convert to JSON const json = JSON.stringify(obj); console.log(json); // ๐Ÿ‘‰๏ธ '{"name": "Tom", "country": "Chile"}' // โœ… Parse back to Object const parsed = JSON.parse(json); console.log(parsed); // ๐Ÿ‘‰๏ธ {name: 'Tom', country: 'Chile'}

We used the JSON.stringify method to convert an object to a JSON string.

The only parameter we passed to the method is the object.

The JSON.stringify method returns a string containing the JSON representation of the object.

index.js
const json = JSON.stringify(obj); console.log(json); // ๐Ÿ‘‰๏ธ '{"name": "Tom", "country": "Chile"}' console.log(typeof json); // ๐Ÿ‘‰๏ธ "string"

If you need to convert the JSON string back to an object, use the JSON.parse() method.

Note that undefined, functions and Symbol values are not valid JSON. If your object contains any of them, they would get omitted when converting the object to a JSON string.

index.js
const obj2 = { id: Symbol('test'), name: undefined, age: () => {}, }; console.log(JSON.stringify(obj2)); // ๐Ÿ‘‰๏ธ {}
None of the key-value pairs of the object got converted to a JSON string, because it only contains JSON incompatible values.

If the object you're converting to a JSON string contains a circular reference, you'd get a TypeError: cyclic object value.

index.js
const obj = { name: 'Tom', country: 'Chile', }; obj.newName = obj; // ๐Ÿ‘‡๏ธ ERROR: Converting circular structure to JSON const json = JSON.stringify(obj);

Because we assigned the object's property to reference the object, we created a circular reference, which throws an exception when converted to JSON.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee