JSON. stringify( ) function in JavaScript

The JSON.stringify() method converts a JavaScript object or value to a JSON string. This is the reverse of JSON.parse() which converts JSON strings back to JavaScript objects.

Syntax

JSON.stringify(value, replacer, space)

Parameters

value: The JavaScript value to convert to JSON string (required)
replacer: Function or array to transform values (optional)
space: Number of spaces or string for indentation (optional)

Basic Example

<html>
<head>
    <title>JSON.stringify Example</title>
</head>
<body>
    <script type="text/javascript">
        var obj = {Tutorial: "JavaScript", Version: "ES6", Active: true};
        var jsonString = JSON.stringify(obj);
        document.write("Object: " + JSON.stringify(obj) + "<br>");
        document.write("Array: " + JSON.stringify([1, 2, 3]) + "<br>");
        document.write("String: " + JSON.stringify("Hello"));
    </script>
</body>
</html>

Output

Object: {"Tutorial":"JavaScript","Version":"ES6","Active":true}
Array: [1,2,3]
String: "Hello"

Using Replacer Function

<html>
<head>
    <title>JSON.stringify with Replacer</title>
</head>
<body>
    <script type="text/javascript">
        var data = {name: "John", age: 30, password: "secret123"};
        
        // Hide password field
        var result = JSON.stringify(data, function(key, value) {
            if (key === "password") return undefined;
            return value;
        });
        
        document.write(result);
    </script>
</body>
</html>

Output

{"name":"John","age":30}

Pretty Formatting with Space Parameter

<html>
<head>
    <title>JSON.stringify Formatted</title>
</head>
<body>
    <script type="text/javascript">
        var obj = {name: "Alice", skills: ["HTML", "CSS", "JS"]};
        var formatted = JSON.stringify(obj, null, 2);
        document.write("<pre>" + formatted + "</pre>");
    </script>
</body>
</html>

Output

{
  "name": "Alice",
  "skills": [
    "HTML",
    "CSS", 
    "JS"
  ]
}

Key Points

  • undefined, functions, and symbols are omitted from objects
  • Date objects are converted to ISO strings
  • NaN and Infinity become null
  • Only enumerable properties are included

Conclusion

JSON.stringify() is essential for converting JavaScript objects to JSON strings for data storage or transmission. Use the optional parameters for custom formatting and filtering.

Updated on: 2026-03-15T23:18:59+05:30

319 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements