JavaScript JSON.stringify() method - JavaScript Tutorial

JavaScript JSON.stringify() method

BLUF: This tutorial on JavaScript JSON.stringify() method provides an in-depth look at JavaScript's core features. It includes practical examples and code snippets to help you master modern JS development.
Key Discovery: JavaScript JSON.stringify() method

Understanding JavaScript JSON.stringify() method is crucial for building dynamic, interactive web applications. Explore the examples below to see it in action.

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:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience