JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

How do I convert a JavaScript object into JSON?

Asked on Aug 25, 2024

Answer

To convert a JavaScript object into JSON, you can use the "JSON.stringify()" method. This method transforms a JavaScript object into a JSON string.
<!-- BEGIN COPY / PASTE -->
        const obj = { name: "John", age: 30, city: "New York" };
        const jsonString = JSON.stringify(obj);
        console.log(jsonString); // Output: {"name":"John","age":30,"city":"New York"}
        <!-- END COPY / PASTE -->
Additional Comment:
  • "JSON.stringify()" is used to convert a JavaScript object to a JSON string.
  • The output is a string that represents the object in JSON format.
  • This method is useful for sending data to a server or storing it in local storage.
✅ Answered with JavaScript best practices.
← Back to All Questions