JavaScript JSON stringify()

Back to JS page

Table of Contents

The JSON.stringify() Method

When sending data to a web server, the data has to be a string.

Convert a JavaScript object into a string with JSON.stringify().

Converting an Object

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>

Example 1

Result View Example

Converting an Array

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>

Example 2

Result View Example

Selecting Properties

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>

Example 3

Result View Example

Formatting JSON

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>

Example 4

Result View Example

Stringifying Dates

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>

Example 5

Result View Example

Document

Document in project

You can Download PDF file.

Reference