Easy Tutorial
❮ Js Howto Js Intro ❯

JavaScript JSON.stringify()

JavaScript JSON


The JSON.stringify() method is used to convert a JavaScript value to a JSON string.

Syntax

JSON.stringify(value[, replacer[, space]])

Parameter Description:

Required. The JavaScript value to convert (usually an object or array).

Optional. A function or array used to transform the result.

If replacer is a function, JSON.stringify will call this function and pass in each member's key and value. The return value is used instead of the original value. If this function returns undefined, the member is excluded. The key of the root object is an empty string: "".

If replacer is an array, only members with keys in this array are converted. The order of conversion is the same as the order of the keys in the array.

Optional. Adds indentation, white space, and line break characters. If space is a number, the returned text is indented by that number of spaces at each level. If space is greater than 10, text is indented by 10 spaces. space can also be a non-numeric value, such as: \t.

Return Value:

Returns a string containing the JSON text.

Example

var str = {"name":"tutorialpro.org", "site":"http://www.tutorialpro.org"}
str_pretty1 = JSON.stringify(str)
document.write( "With only one parameter:" );
document.write( "<br>" );
document.write("<pre>" + str_pretty1 + "</pre>" );

document.write( "<br>" );
str_pretty2 = JSON.stringify(str, null, 4) // Indent with four spaces
document.write( "With parameters:" );
document.write( "<br>" );
document.write("<pre>" + str_pretty2 + "</pre>" ); // pre is used for formatted output

JavaScript JSON

❮ Js Howto Js Intro ❯