Convert Javascript object to JSON String example


Converting a JavaScript object to a JSON String is very easy with the help of JSON.stringify() method.

Let's take a look at an example:


JavaScript Object
const album = {
  name: "Hopes and Fears",
  artist: "Keane",
  year: 2004
};

Convert to JSON Object
const jsonAlbum = JSON.stringify(album);

Print the JSON Object
console.log(jsonAlbum);

Output:

{"name":"Hopes and Fears","artist":"Keane","year":2004}


Note: If the provided JavaScript Object is invalid you will get an SyntaxError while conversion to JSON String.

SyntaxError: Unexpected string literal "Keane". Expected a ':' following the property name 'artist'.

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap