JavaScript JSON stringify() Method
- Previous Page parse()
- Next Page parse()
- Go to the Previous Level JavaScript JSON Reference Manual
Definition and Usage
The JSON.stringify() method converts a JavaScript object to a string.
When sending data to a Web server, the data must be a string.
Instance
Example 1
Stringify a JavaScript object:
var obj = { "name":"Bill", "age":19, "city":"Seattle"}; var myJSON = JSON.stringify(obj); document.getElementById("demo").innerHTML = myJSON;
Example 2
Use a replacement function:
/* Replace the "city" value with uppercase:*/ var obj = { "name":"Bill", "age":"19", "city":"Seattle"}; var text = JSON.stringify(obj, function (key, value) { if (key == "city") { return value.toUpperCase(); } else { return value; } });
Example 3
Usage space Parameters:
/* Insert 10 space characters for each space:*/ var obj = { "name":"Bill", "age":"19", "city":"Seattle"}; var text = JSON.stringify(obj, null, 10);
Example 4
Usage space Parameters:
/* Insert the word SPACE for each space:*/ var obj = { "name":"Bill", "age":"19", "city":"Seattle"}; var text = JSON.stringify(obj, null, "SPACE");
Syntax
JSON.stringify(obj, replacer, space)
Parameter Value
Parameter | Description |
---|---|
obj | Required. The value to be converted to a string. |
replacer |
Optional. A function or array used to convert the result. If the parameter is a function, during the serialization process, each property of the value to be serialized will be converted and processed by this function; If the parameter is an array, only the property names included in this array will be serialized into the final JSON string; If the parameter is null or not provided, all properties of the object will be serialized. |
space |
Optional. A string or numeric value. Specify the whitespace string used for indentation to beautify the output (pretty-print). If the parameter is a number, it represents how many spaces; the maximum is 10. If this value is less than 1, it means there are no spaces; If the parameter is a string (when the string length exceeds 10 letters, take the first 10 letters), the string will be used as spaces; If the parameter is not provided (or is null), there will be no spaces. |
Technical Details
Return Value: | A String |
---|---|
JavaScript Version: | ECMAScript 5 |
Browser Support
The numbers in the table indicate the first browser version that fully supports this method.
Methods | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
stringify() | 4.0 | 8.0 | 3.5 | 4.0 | 11.5 |
Related Pages
JSON Tutorial:Introduction to JSON
- Previous Page parse()
- Next Page parse()
- Go to the Previous Level JavaScript JSON Reference Manual