Name

JSON.stringify() — serialize an object, array or primitive value

Availability

ECMAScript 5

Synopsis

JSON.stringify(o)
JSON.stringify(o, filter)
JSON.stringify(o, filter, indent)

Arguments

o

The object, array, or primitive value to be converted to a JSON string.

filter

An optional function that can replace values before stringification, or an array that contains the names of properties to be stringified.

indent

An optional argument that specifies an indentation string or the number of spaces to use for indentation when formatted human-readable output is desired. If omitted, the returned string contains no extraneous spaces and is machine-readable, but not easily human-readable.

Returns

A JSON-formatted string representing the value o, as filtered by filter and formatted according to indent.

Description

JSON.stringify() converts a primitive value, object or array to a JSON-formatted string that can later be parsed with JSON.parse(). Usually, this function is called with a single argument and returns the corresponding string.

When JSON.stringify() is called with a single argument, and when that value consists only of objects, arrays, strings, numbers, booleans and the null value the stringification is completely straightforward. When the value to be stringified contains objects that are instances of a class, however, the stringification process is more complex. If JSON.stringify() encounters any object (or array) with a method named toJSON(), it invokes that method on the object and stringifies ...

Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.