How to Convert a JavaScript Object to a JSON string (JSON.stringify)

You can’t send JavaScript objects directly to a server, but you can send JSON — a universally accessible string format.

With this code snippet, you can quickly convert JavaScript objects to a JSON string, which allows you to sent your data to your server.

Here’s a JavaScript object representing a single person:

let personObject = {
  name: "Adam",
  age: 25,
  city: "San Diego",
  profession: "Web Developer",
};

To convert the JavaScript object above to JSON, we use a built-in JavaScript function called JSON.stringify(). Add the following right below your JavaScript object:

let personString = JSON.stringify(personObject);

Now if you console.log(personString) the output will be your person object, now represented by a JSON string.

Now your data is ready to be sent to a server!


Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi