JavaScript JSON.stringify(value, replacer, space) method
The JSON.stringify(value, replacer, space)
method in JavaScript is used to convert a JavaScript value (typically an object or array) into a JSON string. This method is part of the JSON
object, which provides utilities for working with JSON data.
Syntax:
Parameters:
value
: The JavaScript value (object, array, etc.) that you want to convert to a JSON string.replacer
(optional): A function or an array that can be used to control the stringification process:- If it's a function, it receives two arguments: the key and the value of each property in the object. You can return a modified value or
undefined
to omit the property from the resulting JSON string. - If it's an array, it specifies the properties to include in the resulting JSON string.
- If it's a function, it receives two arguments: the key and the value of each property in the object. You can return a modified value or
space
(optional): A string or number used to insert white space into the output JSON string for readability:- If it's a number, it specifies the number of spaces to use as white space.
- If it's a string (up to 10 characters), it will be used as white space.
Return Value:
- Returns a JSON string representing the provided value.
Example 1: Basic Usage
In this example, a JavaScript object is converted to a JSON string.
Example 2: Using a Replacer Function
Here, the replacer function excludes the password
property from the resulting JSON string.
Example 3: Using a Replacer Array
In this example, the replacer array specifies that only the name
and age
properties should be included in the JSON string.
Example 4: Using Space for Readability
In this case, the space
parameter is set to 2
, which makes the output JSON string more readable by adding indentation.
Summary:
JSON.stringify(value, replacer, space)
converts a JavaScript value into a JSON string.- The
replacer
parameter can control which properties to include or exclude during the stringification process. - The
space
parameter enhances the readability of the output JSON string by adding indentation. - This method is essential for serializing data for storage or transmission in JSON format.