JavaScript JSON.stringify() method

The JSON.stringify function in JavaScript is utilized to transform a JavaScript value into a JSON-formatted string. When a replacer function is provided, it modifies the values during the conversion process, or if a replacer array is supplied, it includes solely the designated properties in the resulting string.

Syntax

Example

Json.stringify(value[, replacer[, space]])

Parameters

value : The value to convert to a JSON string.

Replacer: A method that modifies how the stringification process is carried out. Its use is not mandatory.

space: An instance of either a String or Number object utilized to introduce whitespace into the resulting JSON string, enhancing its readability. This parameter is not mandatory.

Return value

A JSON string representing the given value.

Browser Support

Chrome Yes
Safari 4
Firefox 3.5
Opera 10.5

JavaScript JSON.stringify method Examples

Example 1

Let’s examine an example of transforming a string object into a JSON string.

Example

<script>

//JavaScript to illustrate JSON.stringify() method.

var json = { firstName:"ASHU", lastName:"BHATI", studentCode:7 };

var student = JSON.stringify(json);

// expected output: {"firstName":"ASHU","lastName":"BHATI","studentCode":7}

document.write(student); 

</script>

Output:

Output

{"firstName":"ASHU","lastName":"BHATI","studentCode":7}

Example 2

Let’s examine an illustration that demonstrates the process of transforming an array object into a JSON string.

Example

<script>

//JavaScript to illustrate JSON.stringify() method.

var a = [ "JAVA", "C", "C++", "Python" ];

var Json = JSON.stringify(a);

// expected output: ["JAVA","C","C++","Python"]

document.write(Json);

</script>

Output:

Output

["JAVA","C","C++","Python"]

Input Required

This code uses input(). Please provide values below: