JSON.stringify
Converts a value to a JSON string.
Available since: ES5
Syntax
JSON.stringify(value, replacer, space)Parameters
| Parameter | Type | Description |
|---|---|---|
| value | any | The value to convert: an object, an array, a string, a number. |
| replacer | Function | Array | Optional. Selects or alters properties. Usually `null` is passed. |
| space | number | Optional. The number of spaces for indentation — makes the result readable. |
Return value
stringA JSON string.
Examples
An object becomes a string:
console.log(JSON.stringify({ name: 'Anna', tags: ['js', 'php'] }));Output:
{"name":"Anna","tags":["js","php"]}The third argument adds indentation:
console.log(JSON.stringify({ name: 'Anna', age: 25 }, null, 2));Output:
{
"name": "Anna",
"age": 25
}Notes
Properties whose value is undefined, and functions, are left out of the result.
See also
- JSON.parse — Parses a JSON string and returns the value.
- structuredClone — Creates a deep copy of an object with all nested data.
- Date.prototype.toISOString — Returns the date in ISO 8601 format in UTC.
Related recipes
- How to compare two arrays
- How to compare two objects
- How to convert an array to a string
- How to convert an object to JSON
- How to copy an object
- How to download a file generated in the browser
- How to inspect a variable while debugging
- How to parse a JSON string
- How to read and write a JSON file in Node.js
- How to save an object to localStorage
In the tutorial
- JSON — The JSON format in JavaScript: turning objects into a string with JSON.stringify and back with JSON.parse.