JavaScript JSON.stringify()
The JSON.stringify() method is used to convert a JavaScript value into a JSON 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 calls that function, passing the key and value of each member. The returned value is used instead of the original value. If the function returns undefined, the member is excluded. The key of the root object is an empty string: "".
If replacer is an array, only members whose keys are in that array are converted. The order of conversion is the same as the order of the keys in the array.
- space:
Optional, adds indentation, spaces, and line breaks to the text. If space is a number, the returned text is indented by that many spaces at each level; if space is greater than 10, the text is indented by 10 spaces. space can also be a non-number, such as: \\t.
Return Value:
Returns a string containing the JSON text.
Example
Example
var
str
=
{
"
name
"
:
"
Runoob Tutorial
"
,
"
site
"
:
"
http://www.runoob.com
"
}
str_pretty1
=
JSON
.
stringify
(
str
)
document
.
write
(
"
With only one parameter:
"
)
;
document
.
write
(
"
"
)
;
document
.
write
(
"
" + str_pretty1 + "
"
)
;
document
.
write
(
"
"
)
;
str_pretty2
=
JSON
.
stringify
(
str
,
null
,
4
)
//
Using four spaces for indentation
document
.
write
(
"
Using the parameter:
"
)
;
document
.
write
(
"
"
)
;
document
.
write
(
"
" + str_pretty2 + "
"
)
;
//
pre is used to format the output
Try it »
JavaScript JSON