JSON.stringify()
JSON is often used to exchange data with the server.
When sending data to the server, it is generally a string.
We can use the JSON.stringify() method to convert a JavaScript object to a string.
Syntax
JSON.stringify(value[, replacer[, space]])
Parameter description:
- value:
Required. The JavaScript value to convert (usually an object or array).
- replacer:
Optional. A function or array used to transform the result.
If replacer is a function, JSON.stringify will call that function, passing in the key and value of each member. The return value is used instead of the original value. If this function returns undefined, the member is excluded. The key for the root object is an empty string: "".
If replacer is an array, only members with key values present in the array are converted. The conversion order of members is the same as the order of keys in the array. When the value parameter is also an array, the replacer array is ignored.
- space:
Optional. Adds indentation, spaces, and line breaks to the text. If space is a number, the return value text is indented by the specified number of spaces at each level. If space is greater than 10, the text is indented 10 spaces. space can also be a non-number, such as \t.
JavaScript Object Conversion
For example, we send the following data to the server:
We use the JSON.stringify() method to process the above data and convert it to a string:
myJSON is a string.
We can send myJSON to the server:
Example
Try it Yourself »
JavaScript Array Conversion
We can also convert a JavaScript array into a JSON string:
Example
myJSON is a string.
We can send myJSON to the server:
Example
Try it Yourself »
Exceptions
Parsing Data
JSON cannot store Date objects.
JSON.stringify() will convert all dates to strings.
Example
Try it Yourself »
After that, you can convert the string back into a Date object.
Parsing Functions
JSON does not allow functions. JSON.stringify() will remove functions from JavaScript objects, including the key and value.
Example
Try it Yourself »
We can avoid the above problem by converting the function to a string before executing the JSON.stringify() function:
Example
Try it Yourself »
It is not recommended to use functions in JSON.
Browser Support
Mainstream browsers all support the JSON.stringify() function:
- Firefox 3.5
- Internet Explorer 8
- Chrome
- Opera 10
- Safari 4