Convert javascript object to JSON using JSON stringify method with examples
Contents
JSON.stringify() function:
The Javascript function JSON.stringify() is used to convert the javascript object to JSON string.
Syntax for JSON.stringify():
1 2 3 |
JSON.stringify(value, replacer, space) |
Explanation:
value: The value to convert to a JSON string.
replacer : It is a optional parameter. A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string.
space : It is also an optional parameter. This argument is used to control spacing in the final string generated using JSON.stringify() function. It can be number or a string if it is a number than the specified number of spaces indented to the final string and if it is a string then that string is (upto 10 characters) used for indentation.
Return Value: It returns a JSON string for a given value.
Example :
1 2 3 4 5 6 7 8 9 10 11 |
<script> var jsObject = { firstname:"Michael", lastname:"Josh", age:"28" }; document.write("Source data type:"+typeof(jsObject) + "<br>"); var jsonString = JSON.stringify(jsObject); document.write("Output data type:" +typeof(jsonString) + "<br>"); document.write("Output :" + jsonString); </script> |
The variable jsObject declared as a Javascript object and it contains the value of a person details.The typeof is a operator that returns the type of a variable or an expression.
Then the JSON.stringify() function is converts the jsObject to JSON string.We can write the output using the document.write() method and it confirms that before JSON.stringify() function,the variable is Javascript object and after JSON.stringify() function,the variable is a JSON.
Output:
Source data type:object
Output data type:string
Output :{“firstname”:”Michael”,”lastname”:”Josh”,”age”:”28″}