The Wayback Machine - http://web.archive.org/web/20220710174208/https://www.geeksforgeeks.org/javascript-json-stringify-method/amp/

JavaScript JSON stringify() Method

The JSON.stringify() method in Javascript is used to create a JSON string out of it. While developing an application using JavaScript, many times it is needed to serialize the data to strings for storing the data into a database or for sending the data to an API or web server. The data has to be in the form of strings. This conversion of an object to a string can be easily done with the help of the JSON.stringify() method.

Syntax:

JSON.stringify(value, replacer, space);

Parameters: This method accepts three parameters as mentioned above and described below:

Return Value: It returns a string for a given value.

Example: The below example illustrates the JSON signify() method in JavaScript:



var value = { name: "Logan", age: 21, location: "London" };
var result = JSON.stringify(value);

Output:
{"name":"Logan", "age":21, "location":"London"}

Example: The below is the example of the JSON stringify() Method. 




<script>
    const value = {
        Company: "GeeksforGeeks",
        Estd: 2009,
        location: "Noida"
    };
    const result = JSON.stringify(value);
    document.write("value of result = " + result + "<br>");
</script>

Output:

value of result = {"Company":"GeeksforGeeks",
                   "Estd":2009,
                   "location":"Noida"}

More example codes for the above method are as follows: 

Program 1: In the below code, the JavaScript object is being passed as a value in the function to convert it into a string.




<script>
    var value = {
        name: "Logan",
        age: 21,
        location: "London"
    };
    var result = JSON.stringify(value);
    document.write("value of result = " + result + "<br>");
    document.write("type of result = " + typeof result);
</script>

Output:

value of result = {"name":"Logan", "age":21, "location":"London"}
type of result = string

Program 2: In the below code will look over as it is helpful to convert it into string without doing changes in original object so helpful for nested object to changes without reflecting in original object.




let obj = {
    name: "GFG",
    add : {
        country: "India",
        state : {
            code : "JS",
            topic : "stringify"
        }
    }
}
 
let obj2 = JSON.parse(JSON.stringify(obj));
obj2.add.state.topic  = "stringify json object";
console.log(obj);
console.log(obj2);


 

Program 3: In the below code, the JavaScript array can be passed as a value in the function to convert it into a string.




<script>
    var value = ["Logan", 21, "Peter", 24];
    var result = JSON.stringify(value);
    document.write("value of result = " + result + "<br>");
    document.write("type of result = " + typeof result);
</script>

Output:

value of result = ["Logan", 21, "Peter", 24]
type of result = string

Supported browsers:




Article Tags :