Table of Contents
When sending data to a web server, the data has to be a string.
Convert a JavaScript object into a string with JSON.stringify().
JSON.stringify() converts a JavaScript object into a JSON string:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript JSON stringify()</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>
<h4>Converting an Object</h4>
<p id="demo"></p>
<script>
const obj = {name: "John", age: 30, city: "New York"};
const jsonString = JSON.stringify(obj);
document.getElementById("demo").innerHTML = jsonString;
</script>
</body>
</html>

Result View Example
JSON.stringify() can also convert a JavaScript array into a JSON string:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript JSON stringify()</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>
<h4>Converting an Array</h4>
<p id="demo"></p>
<script>
const arr = ["Ford", "BMW", "Audi", "Fiat"];
const jsonString = JSON.stringify(arr);
document.getElementById("demo").innerHTML = jsonString;
</script>
</body>
</html>

Result View Example
The JSON.stringify() method can accept a replacer array to select which properties to include:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript JSON stringify()</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>
<h4>Selecting Properties</h4>
<p id="demo"></p>
<script>
const obj = {name: "John", age: 30, city: "New York", country: "USA"};
const jsonString = JSON.stringify(obj, ["name", "city"]);
document.getElementById("demo").innerHTML = jsonString;
</script>
</body>
</html>

Result View Example
The JSON.stringify() method can accept a space parameter to format the output with spaces:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript JSON stringify()</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>
<h4>Formatting JSON</h4>
<pre id="demo"></pre>
<script>
const obj = {name: "John", age: 30, city: "New York", hobbies: ["reading", "music"]};
const jsonString = JSON.stringify(obj, null, 2);
document.getElementById("demo").innerHTML = jsonString;
</script>
</body>
</html>

Result View Example
Dates are converted to strings when using JSON.stringify():
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript JSON stringify()</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>
<h4>Stringifying Dates</h4>
<p id="demo"></p>
<script>
const obj = {name: "John", today: new Date(), city: "New York"};
const jsonString = JSON.stringify(obj);
document.getElementById("demo").innerHTML = jsonString;
</script>
</body>
</html>

Result View Example
Document in project
You can Download PDF file.