🕷️ Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

Query:
Response:
Calculated Shard: 53 (from laksa026)

2. Crawled Status Check

Query:
Response:

3. Robots.txt Check

Query:
Response:

4. Spam/Ban Check

Query:
Response:

5. Seen Status Check

ℹ️ Skipped - page is already crawled

đź“„
INDEXABLE
âś…
CRAWLED
16 hours ago
🤖
ROBOTS ALLOWED

Page Info Filters

FilterStatusConditionDetails
HTTP statusPASSdownload_http_code = 200HTTP 200
Age cutoffPASSdownload_stamp > now() - 6 MONTH0 months ago
History dropPASSisNull(history_drop_reason)No drop reason
Spam/banPASSfh_dont_index != 1 AND ml_spam_score = 0ml_spam_score=0
CanonicalPASSmeta_canonical IS NULL OR = '' OR = src_unparsedNot set

Page Details

PropertyValue
URLhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
Last Crawled2026-04-16 09:01:14 (16 hours ago)
First Indexed2013-08-08 16:27:31 (12 years ago)
HTTP Status Code200
Meta TitleJSON.stringify() - JavaScript | MDN
Meta DescriptionThe JSON.stringify() static method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
Meta Canonicalnull
Boilerpipe Text
Try it console.log(JSON.stringify({ x: 5, y: 6 })); // Expected output: '{"x":5,"y":6}' console.log( JSON.stringify([new Number(3), new String("false"), new Boolean(false)]), ); // Expected output: '[3,"false",false]' console.log(JSON.stringify({ x: [10, undefined, function () {}, Symbol("")] })); // Expected output: '{"x":[10,null,null,null]}' console.log(JSON.stringify(new Date(2006, 0, 2, 15, 4, 5))); // Expected output: '"2006-01-02T15:04:05.000Z"' Syntax js JSON.stringify(value) JSON.stringify(value, replacer) JSON.stringify(value, replacer, space) Parameters value The value to convert to a JSON string. replacer Optional A function that alters the behavior of the stringification process, or an array of strings and numbers that specifies properties of value to be included in the output. If replacer is an array, all elements in this array that are not strings or numbers (either primitives or wrapper objects), including Symbol values, are completely ignored. If replacer is anything other than a function or an array (e.g., null or not provided), all string-keyed properties of the object are included in the resulting JSON string. space Optional A string or number that's used to insert white space (including indentation, line break characters, etc.) into the output JSON string for readability purposes. If this is a number, it indicates the number of space characters to be used as indentation, clamped to 10 (that is, any number greater than 10 is treated as if it were 10 ). Values less than 1 indicate that no space should be used. If this is a string, the string (or the first 10 characters of the string, if it's longer than that) is inserted before every nested object or array. If space is anything other than a string or number (can be either a primitive or a wrapper object) — for example, is null or not provided — no white space is used. Return value A JSON string representing the given value, or undefined. Exceptions TypeError Thrown in one of the following cases: value contains a circular reference. A BigInt value is encountered. Description JSON.stringify() converts a value to the JSON notation that the value represents. Values are stringified in the following manner: Boolean , Number , String , and BigInt (obtainable via Object() ) objects are converted to the corresponding primitive values during stringification, in accordance with the traditional conversion semantics. Symbol objects (obtainable via Object() ) are treated as plain objects. Attempting to serialize BigInt values will throw. However, if the BigInt has a toJSON() method (through monkey patching: BigInt.prototype.toJSON = ... ), that method can provide the serialization result. This constraint ensures that a proper serialization (and, very likely, its accompanying deserialization) behavior is always explicitly provided by the user. undefined , Function , and Symbol values are not valid JSON values. If any such values are encountered during conversion, they are either omitted (when found in an object) or changed to null (when found in an array). JSON.stringify() can return undefined when passing in "pure" values like JSON.stringify(() => {}) or JSON.stringify(undefined) . The numbers Infinity and NaN , as well as the value null , are all considered null . (But unlike the values in the previous point, they would never be omitted.) Arrays are serialized as arrays (enclosed by square brackets). Only array indices between 0 and length - 1 (inclusive) are serialized; other properties are ignored. The special raw JSON object created with JSON.rawJSON() is serialized as the raw JSON text it contains (by accessing its rawJSON property). For other objects: All Symbol -keyed properties will be completely ignored, even when using the replacer parameter. If the value has a toJSON() method, it's responsible to define what data will be serialized. Instead of the object being serialized, the value returned by the toJSON() method when called will be serialized. JSON.stringify() calls toJSON with one parameter, the key , which has the same semantic as the key parameter of the replacer function: if this object is a property value, the property name if it is in an array, the index in the array, as a string if JSON.stringify() was directly called on this object, an empty string All Temporal objects implement the toJSON() method, which returns a string (the same as calling toString() ). Thus, they will be serialized as strings. Similarly, Date objects implement toJSON() , which returns the same as toISOString() . Only enumerable own properties are visited. This means Map , Set , etc. will become "{}" . You can use the replacer parameter to serialize them to something more useful. Properties are visited using the same algorithm as Object.keys() , which has a well-defined order and is stable across implementations. For example, JSON.stringify on the same object will always produce the same string, and JSON.parse(JSON.stringify(obj)) would produce an object with the same key ordering as the original (assuming the object is completely JSON-serializable). The replacer parameter The replacer parameter can be either a function or an array. As an array, its elements indicate the names of the properties in the object that should be included in the resulting JSON string. Only string and number values are taken into account; symbol keys are ignored. As a function, it takes two parameters: the key and the value being stringified. The object in which the key was found is provided as the replacer 's this context. The replacer function is called for the initial object being stringified as well, in which case the key is an empty string ( "" ). It is then called for each property on the object or array being stringified. Array indices will be provided in its string form as key . The current property value will be replaced with the replacer 's return value for stringification. This means: If you return a number, string, boolean, or null , that value is directly serialized and used as the property's value. (Returning a BigInt will throw as well.) If you return a Function , Symbol , or undefined , the property is not included in the output. If you return any other object, the object is recursively stringified, calling the replacer function on each property. Note: When parsing JSON generated with replacer functions, you would likely want to use the reviver parameter to perform the reverse operation. Typically, array elements' index would never shift (even when the element is an invalid value like a function, it will become null instead of omitted). Using the replacer function allows you to control the order of the array elements by returning a different array. The space parameter The space parameter may be used to control spacing in the final string. If it is a number, successive levels in the stringification will each be indented by this many space characters. If it is a string, successive levels will be indented by this string. Each level of indentation will never be longer than 10. Number values of space are clamped to 10, and string values are truncated to 10 characters. Examples Using JSON.stringify js JSON.stringify({}); // '{}' JSON.stringify(true); // 'true' JSON.stringify("foo"); // '"foo"' JSON.stringify([1, "false", false]); // '[1,"false",false]' JSON.stringify([NaN, null, Infinity]); // '[null,null,null]' JSON.stringify({ x: 5 }); // '{"x":5}' JSON.stringify(new Date(1906, 0, 2, 15, 4, 5)); // '"1906-01-02T15:04:05.000Z"' JSON.stringify({ x: 5, y: 6 }); // '{"x":5,"y":6}' JSON.stringify([new Number(3), new String("false"), new Boolean(false)]); // '[3,"false",false]' // String-keyed array elements are not enumerable and make no sense in JSON const a = ["foo", "bar"]; a["baz"] = "quux"; // a: [ 0: 'foo', 1: 'bar', baz: 'quux' ] JSON.stringify(a); // '["foo","bar"]' JSON.stringify({ x: [10, undefined, function () {}, Symbol("")] }); // '{"x":[10,null,null,null]}' // Standard data structures JSON.stringify([ new Set([1]), new Map([[1, 2]]), new WeakSet([{ a: 1 }]), new WeakMap([[{ a: 1 }, 2]]), ]); // '[{},{},{},{}]' // TypedArray JSON.stringify([new Int8Array([1]), new Int16Array([1]), new Int32Array([1])]); // '[{"0":1},{"0":1},{"0":1}]' JSON.stringify([ new Uint8Array([1]), new Uint8ClampedArray([1]), new Uint16Array([1]), new Uint32Array([1]), ]); // '[{"0":1},{"0":1},{"0":1},{"0":1}]' JSON.stringify([new Float32Array([1]), new Float64Array([1])]); // '[{"0":1},{"0":1}]' // toJSON() JSON.stringify({ x: 5, y: 6, toJSON() { return this.x + this.y; }, }); // '11' // Symbols: JSON.stringify({ x: undefined, y: Object, z: Symbol("") }); // '{}' JSON.stringify({ [Symbol("foo")]: "foo" }); // '{}' JSON.stringify({ [Symbol.for("foo")]: "foo" }, [Symbol.for("foo")]); // '{}' JSON.stringify({ [Symbol.for("foo")]: "foo" }, (k, v) => { if (typeof k === "symbol") { return "a symbol"; } }); // undefined // Non-enumerable properties: JSON.stringify( Object.create(null, { x: { value: "x", enumerable: false }, y: { value: "y", enumerable: true }, }), ); // '{"y":"y"}' // BigInt values throw JSON.stringify({ x: 2n }); // TypeError: BigInt value can't be serialized in JSON Using a function as replacer js function replacer(key, value) { // Filtering out properties if (typeof value === "string") { return undefined; } return value; } const foo = { foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7, }; JSON.stringify(foo, replacer); // '{"week":45,"month":7}' If you wish the replacer to distinguish an initial object from a key with an empty string property (since both would give the empty string as key and potentially an object as value), you will have to keep track of the iteration count (if it is beyond the first iteration, it is a genuine empty string key). js function makeReplacer() { let isInitial = true; return (key, value) => { if (isInitial) { isInitial = false; return value; } if (key === "") { // Omit all properties with name "" (except the initial object) return undefined; } return value; }; } const replacer = makeReplacer(); console.log(JSON.stringify({ "": 1, b: 2 }, replacer)); // "{"b":2}" Using an array as replacer js const foo = { foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7, }; JSON.stringify(foo, ["week", "month"]); // '{"week":45,"month":7}', only keep "week" and "month" properties Using the space parameter Indent the output with one space: js console.log(JSON.stringify({ a: 2 }, null, " ")); /* { "a": 2 } */ Using a tab character mimics standard pretty-print appearance: js console.log(JSON.stringify({ uno: 1, dos: 2 }, null, "\t")); /* { "uno": 1, "dos": 2 } */ toJSON() behavior Defining toJSON() for an object allows overriding its serialization behavior. js const obj = { data: "data", toJSON(key) { return key ? `Now I am a nested object under key '${key}'` : this; }, }; JSON.stringify(obj); // '{"data":"data"}' JSON.stringify({ obj }); // '{"obj":"Now I am a nested object under key 'obj'"}' JSON.stringify([obj]); // '["Now I am a nested object under key '0'"]' Issue with serializing circular references Since the JSON format doesn't support object references (although an IETF draft exists ), a TypeError will be thrown if one attempts to encode an object with circular references. js const circularReference = {}; circularReference.myself = circularReference; // Serializing circular references throws "TypeError: cyclic object value" JSON.stringify(circularReference); To serialize circular references, you can use a library that supports them (e.g., cycle.js by Douglas Crockford) or implement a solution yourself, which will require finding and replacing (or removing) the cyclic references by serializable values. If you are using JSON.stringify() to deep-copy an object, you may instead want to use structuredClone() , which supports circular references. JavaScript engine APIs for binary serialization, such as v8.serialize() , also support circular references. Using JSON.stringify() with localStorage In a case where you want to store an object created by your user and allow it to be restored even after the browser has been closed, the following example is a model for the applicability of JSON.stringify() : js // Creating an example of JSON const session = { screens: [], state: true, }; session.screens.push({ name: "screenA", width: 450, height: 250 }); session.screens.push({ name: "screenB", width: 650, height: 350 }); session.screens.push({ name: "screenC", width: 750, height: 120 }); session.screens.push({ name: "screenD", width: 250, height: 60 }); session.screens.push({ name: "screenE", width: 390, height: 120 }); session.screens.push({ name: "screenF", width: 1240, height: 650 }); // Converting the JSON string with JSON.stringify() // then saving with localStorage in the name of session localStorage.setItem("session", JSON.stringify(session)); // Example of how to transform the String generated through // JSON.stringify() and saved in localStorage in JSON object again const restoredSession = JSON.parse(localStorage.getItem("session")); // Now restoredSession variable contains the object that was saved // in localStorage console.log(restoredSession); Well-formed JSON.stringify() Engines implementing the well-formed JSON.stringify specification will stringify lone surrogates (any code point from U+D800 to U+DFFF) using Unicode escape sequences rather than literally (outputting lone surrogates). Before this change, such strings could not be encoded in valid UTF-8 or UTF-16: js JSON.stringify("\uD800"); // '"�"' But with this change JSON.stringify() represents lone surrogates using JSON escape sequences that can be encoded in valid UTF-8 or UTF-16: js JSON.stringify("\uD800"); // '"\\ud800"' This change should be backwards-compatible as long as you pass the result of JSON.stringify() to APIs such as JSON.parse() that will accept any valid JSON text, because they will treat Unicode escapes of lone surrogates as identical to the lone surrogates themselves. Only if you are directly interpreting the result of JSON.stringify() do you need to carefully handle JSON.stringify() 's two possible encodings of these code points. Specifications Specification ECMAScript® 2027 Language Specification # sec-json.stringify Browser compatibility See also Polyfill of modern JSON.stringify behavior (symbol, well-formed unicode, raw JSON) in core-js JSON.parse() JSON.rawJSON()
Markdown
- [Skip to main content](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#content) - [Skip to search](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#search) HTML [HTML: Markup language](https://developer.mozilla.org/en-US/docs/Web/HTML) HTML reference - [Elements](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements) - [Global attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes) - [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes) - [See all…](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference "See all HTML references") HTML guides - [Responsive images](https://developer.mozilla.org/en-US/docs/Web/HTML/Guides/Responsive_images) - [HTML cheatsheet](https://developer.mozilla.org/en-US/docs/Web/HTML/Guides/Cheatsheet) - [Date & time formats](https://developer.mozilla.org/en-US/docs/Web/HTML/Guides/Date_and_time_formats) - [See all…](https://developer.mozilla.org/en-US/docs/Web/HTML/Guides "See all HTML guides") Markup languages - [SVG](https://developer.mozilla.org/en-US/docs/Web/SVG) - [MathML](https://developer.mozilla.org/en-US/docs/Web/MathML) - [XML](https://developer.mozilla.org/en-US/docs/Web/XML) CSS [CSS: Styling language](https://developer.mozilla.org/en-US/docs/Web/CSS) CSS reference - [Properties](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties) - [Selectors](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Selectors) - [At-rules](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/At-rules) - [Values](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Values) - [See all…](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference "See all CSS references") CSS guides - [Box model](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Box_model/Introduction) - [Animations](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Animations/Using) - [Flexbox](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Flexible_box_layout/Basic_concepts) - [Colors](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Colors/Applying_color) - [See all…](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides "See all CSS guides") Layout cookbook - [Column layouts](https://developer.mozilla.org/en-US/docs/Web/CSS/How_to/Layout_cookbook/Column_layouts) - [Centering an element](https://developer.mozilla.org/en-US/docs/Web/CSS/How_to/Layout_cookbook/Center_an_element) - [Card component](https://developer.mozilla.org/en-US/docs/Web/CSS/How_to/Layout_cookbook/Card) - [See all…](https://developer.mozilla.org/en-US/docs/Web/CSS/How_to/Layout_cookbook) JavaScriptJS [JavaScript: Scripting language](https://developer.mozilla.org/en-US/docs/Web/JavaScript) JS reference - [Standard built-in objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects) - [Expressions & operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators) - [Statements & declarations](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements) - [Functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions) - [See all…](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference "See all JavaScript references") JS guides - [Control flow & error handing](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling) - [Loops and iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration) - [Working with objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_objects) - [Using classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_classes) - [See all…](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide "See all JavaScript guides") Web APIs [Web APIs: Programming interfaces](https://developer.mozilla.org/en-US/docs/Web/API) Web API reference - [File system API](https://developer.mozilla.org/en-US/docs/Web/API/File_System_API) - [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) - [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API) - [HTML DOM API](https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API) - [Push API](https://developer.mozilla.org/en-US/docs/Web/API/Push_API) - [Service worker API](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) - [See all…](https://developer.mozilla.org/en-US/docs/Web/API "See all Web API guides") Web API guides - [Using the Web animation API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API/Using_the_Web_Animations_API) - [Using the Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) - [Working with the History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API/Working_with_the_History_API) - [Using the Web speech API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Speech_API/Using_the_Web_Speech_API) - [Using web workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) All [All web technology](https://developer.mozilla.org/en-US/docs/Web) Technologies - [Accessibility](https://developer.mozilla.org/en-US/docs/Web/Accessibility) - [HTTP](https://developer.mozilla.org/en-US/docs/Web/HTTP) - [URI](https://developer.mozilla.org/en-US/docs/Web/URI) - [Web extensions](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions) - [WebAssembly](https://developer.mozilla.org/en-US/docs/WebAssembly) - [WebDriver](https://developer.mozilla.org/en-US/docs/Web/WebDriver) - [See all…](https://developer.mozilla.org/en-US/docs/Web "See all web technology references") Topics - [Media](https://developer.mozilla.org/en-US/docs/Web/Media) - [Performance](https://developer.mozilla.org/en-US/docs/Web/Performance) - [Privacy](https://developer.mozilla.org/en-US/docs/Web/Privacy) - [Security](https://developer.mozilla.org/en-US/docs/Web/Security) - [Progressive web apps](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps) Learn [Learn web development](https://developer.mozilla.org/en-US/docs/Learn_web_development) Frontend developer course - [Getting started modules](https://developer.mozilla.org/en-US/docs/Learn_web_development/Getting_started) - [Core modules](https://developer.mozilla.org/en-US/docs/Learn_web_development/Core) - [MDN Curriculum](https://developer.mozilla.org/en-US/curriculum/) - [Check out the video course from Scrimba, our partner](https://scrimba.com/frontend-path-c0j?via=mdn-learn-navbar) Learn HTML - [Structuring content with HTML module](https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Structuring_content) Learn CSS - [CSS styling basics module](https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Styling_basics) - [CSS layout module](https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/CSS_layout) Learn JavaScript - [Dynamic scripting with JavaScript module](https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Scripting) Tools Discover our tools - [Playground](https://developer.mozilla.org/en-US/play) - [HTTP Observatory](https://developer.mozilla.org/en-US/observatory) - [Border-image generator](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Backgrounds_and_borders/Border-image_generator) - [Border-radius generator](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Backgrounds_and_borders/Border-radius_generator) - [Box-shadow generator](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Backgrounds_and_borders/Box-shadow_generator) - [Color format converter](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Colors/Color_format_converter) - [Color mixer](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Colors/Color_mixer) - [Shape generator](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Shapes/Shape_generator) About Get to know MDN better - [About MDN](https://developer.mozilla.org/en-US/about) - [Advertise with us](https://developer.mozilla.org/en-US/advertising) - [Community](https://developer.mozilla.org/en-US/community) - [MDN on GitHub](https://github.com/mdn) [Blog](https://developer.mozilla.org/en-US/blog/) 1. [Web](https://developer.mozilla.org/en-US/docs/Web) 2. [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript) 3. [Reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference) 4. [Standard built-in objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects) 5. [JSON](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON) 6. [stringify()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) # JSON.stringify() Baseline Widely available This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015. - [Learn more](https://developer.mozilla.org/en-US/docs/Glossary/Baseline/Compatibility) - [See full compatibility](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#browser_compatibility) - [Report feedback](https://survey.alchemer.com/s3/7634825/MDN-baseline-feedback?page=%2Fen-US%2Fdocs%2FWeb%2FJavaScript%2FReference%2FGlobal_Objects%2FJSON%2Fstringify&level=high) The **`JSON.stringify()`** static method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified. ## In this article - [Try it](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#try_it) - [Syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#syntax) - [Description](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#description) - [Examples](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#examples) - [Specifications](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#specifications) - [Browser compatibility](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#browser_compatibility) - [See also](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#see_also) ## [Try it](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#try_it) ``` console.log(JSON.stringify({ x: 5, y: 6 })); // Expected output: '{"x":5,"y":6}' console.log( JSON.stringify([new Number(3), new String("false"), new Boolean(false)]), ); // Expected output: '[3,"false",false]' console.log(JSON.stringify({ x: [10, undefined, function () {}, Symbol("")] })); // Expected output: '{"x":[10,null,null,null]}' console.log(JSON.stringify(new Date(2006, 0, 2, 15, 4, 5))); // Expected output: '"2006-01-02T15:04:05.000Z"' ``` ## [Syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#syntax) js ``` JSON.stringify(value) JSON.stringify(value, replacer) JSON.stringify(value, replacer, space) ``` ### [Parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#parameters) [`value`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#value) The value to convert to a JSON string. [`replacer` Optional](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#replacer) A function that alters the behavior of the stringification process, or an array of strings and numbers that specifies properties of `value` to be included in the output. If `replacer` is an array, all elements in this array that are not strings or numbers (either primitives or wrapper objects), including [`Symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) values, are completely ignored. If `replacer` is anything other than a function or an array (e.g., [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/null) or not provided), all string-keyed properties of the object are included in the resulting JSON string. [`space` Optional](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#space) A string or number that's used to insert white space (including indentation, line break characters, etc.) into the output JSON string for readability purposes. If this is a number, it indicates the number of space characters to be used as indentation, clamped to 10 (that is, any number greater than `10` is treated as if it were `10`). Values less than 1 indicate that no space should be used. If this is a string, the string (or the first 10 characters of the string, if it's longer than that) is inserted before every nested object or array. If `space` is anything other than a string or number (can be either a primitive or a wrapper object) — for example, is [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/null) or not provided — no white space is used. ### [Return value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#return_value) A JSON string representing the given value, or undefined. ### [Exceptions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#exceptions) [`TypeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) Thrown in one of the following cases: - `value` contains a circular reference. - A [`BigInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) value is encountered. ## [Description](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#description) `JSON.stringify()` converts a value to the JSON notation that the value represents. Values are stringified in the following manner: - [`Boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean), [`Number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number), [`String`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String), and [`BigInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) (obtainable via [`Object()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) objects are converted to the corresponding primitive values during stringification, in accordance with the traditional conversion semantics. [`Symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) objects (obtainable via [`Object()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) are treated as plain objects. - Attempting to serialize [`BigInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) values will throw. However, if the BigInt has a `toJSON()` method (through monkey patching: `BigInt.prototype.toJSON = ...`), that method can provide the serialization result. This constraint ensures that a proper serialization (and, very likely, its accompanying deserialization) behavior is always explicitly provided by the user. - [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined), [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function), and [`Symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) values are not valid JSON values. If any such values are encountered during conversion, they are either omitted (when found in an object) or changed to [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/null) (when found in an array). `JSON.stringify()` can return `undefined` when passing in "pure" values like `JSON.stringify(() => {})` or `JSON.stringify(undefined)`. - The numbers [`Infinity`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Infinity) and [`NaN`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN), as well as the value [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/null), are all considered `null`. (But unlike the values in the previous point, they would never be omitted.) - Arrays are serialized as arrays (enclosed by square brackets). Only array indices between 0 and `length - 1` (inclusive) are serialized; other properties are ignored. - The special raw JSON object created with [`JSON.rawJSON()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/rawJSON) is serialized as the raw JSON text it contains (by accessing its `rawJSON` property). - For other objects: - All [`Symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol)\-keyed properties will be completely ignored, even when using the [`replacer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_replacer_parameter) parameter. - If the value has a `toJSON()` method, it's responsible to define what data will be serialized. Instead of the object being serialized, the value returned by the `toJSON()` method when called will be serialized. `JSON.stringify()` calls `toJSON` with one parameter, the `key`, which has the same semantic as the `key` parameter of the [`replacer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_replacer_parameter) function: - if this object is a property value, the property name - if it is in an array, the index in the array, as a string - if `JSON.stringify()` was directly called on this object, an empty string All [`Temporal`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal) objects implement the `toJSON()` method, which returns a string (the same as calling `toString()`). Thus, they will be serialized as strings. Similarly, [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) objects implement `toJSON()`, which returns the same as [`toISOString()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString). - Only [enumerable own properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Enumerability_and_ownership_of_properties) are visited. This means [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map), [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set), etc. will become `"{}"`. You can use the [`replacer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_replacer_parameter) parameter to serialize them to something more useful. Properties are visited using the same algorithm as [`Object.keys()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys), which has a well-defined order and is stable across implementations. For example, `JSON.stringify` on the same object will always produce the same string, and `JSON.parse(JSON.stringify(obj))` would produce an object with the same key ordering as the original (assuming the object is completely JSON-serializable). ### [The replacer parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_replacer_parameter) The `replacer` parameter can be either a function or an array. As an array, its elements indicate the names of the properties in the object that should be included in the resulting JSON string. Only string and number values are taken into account; symbol keys are ignored. As a function, it takes two parameters: the `key` and the `value` being stringified. The object in which the key was found is provided as the `replacer`'s `this` context. The `replacer` function is called for the initial object being stringified as well, in which case the `key` is an empty string (`""`). It is then called for each property on the object or array being stringified. Array indices will be provided in its string form as `key`. The current property value will be replaced with the `replacer`'s return value for stringification. This means: - If you return a number, string, boolean, or `null`, that value is directly serialized and used as the property's value. (Returning a BigInt will throw as well.) - If you return a [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function), [`Symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol), or [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined), the property is not included in the output. - If you return any other object, the object is recursively stringified, calling the `replacer` function on each property. **Note:** When parsing JSON generated with `replacer` functions, you would likely want to use the [`reviver`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#using_the_reviver_parameter) parameter to perform the reverse operation. Typically, array elements' index would never shift (even when the element is an invalid value like a function, it will become `null` instead of omitted). Using the `replacer` function allows you to control the order of the array elements by returning a different array. ### [The space parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_space_parameter) The `space` parameter may be used to control spacing in the final string. - If it is a number, successive levels in the stringification will each be indented by this many space characters. - If it is a string, successive levels will be indented by this string. Each level of indentation will never be longer than 10. Number values of `space` are clamped to 10, and string values are truncated to 10 characters. ## [Examples](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#examples) ### [Using JSON.stringify](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#using_json.stringify) js ``` JSON.stringify({}); // '{}' JSON.stringify(true); // 'true' JSON.stringify("foo"); // '"foo"' JSON.stringify([1, "false", false]); // '[1,"false",false]' JSON.stringify([NaN, null, Infinity]); // '[null,null,null]' JSON.stringify({ x: 5 }); // '{"x":5}' JSON.stringify(new Date(1906, 0, 2, 15, 4, 5)); // '"1906-01-02T15:04:05.000Z"' JSON.stringify({ x: 5, y: 6 }); // '{"x":5,"y":6}' JSON.stringify([new Number(3), new String("false"), new Boolean(false)]); // '[3,"false",false]' // String-keyed array elements are not enumerable and make no sense in JSON const a = ["foo", "bar"]; a["baz"] = "quux"; // a: [ 0: 'foo', 1: 'bar', baz: 'quux' ] JSON.stringify(a); // '["foo","bar"]' JSON.stringify({ x: [10, undefined, function () {}, Symbol("")] }); // '{"x":[10,null,null,null]}' // Standard data structures JSON.stringify([ new Set([1]), new Map([[1, 2]]), new WeakSet([{ a: 1 }]), new WeakMap([[{ a: 1 }, 2]]), ]); // '[{},{},{},{}]' // TypedArray JSON.stringify([new Int8Array([1]), new Int16Array([1]), new Int32Array([1])]); // '[{"0":1},{"0":1},{"0":1}]' JSON.stringify([ new Uint8Array([1]), new Uint8ClampedArray([1]), new Uint16Array([1]), new Uint32Array([1]), ]); // '[{"0":1},{"0":1},{"0":1},{"0":1}]' JSON.stringify([new Float32Array([1]), new Float64Array([1])]); // '[{"0":1},{"0":1}]' // toJSON() JSON.stringify({ x: 5, y: 6, toJSON() { return this.x + this.y; }, }); // '11' // Symbols: JSON.stringify({ x: undefined, y: Object, z: Symbol("") }); // '{}' JSON.stringify({ [Symbol("foo")]: "foo" }); // '{}' JSON.stringify({ [Symbol.for("foo")]: "foo" }, [Symbol.for("foo")]); // '{}' JSON.stringify({ [Symbol.for("foo")]: "foo" }, (k, v) => { if (typeof k === "symbol") { return "a symbol"; } }); // undefined // Non-enumerable properties: JSON.stringify( Object.create(null, { x: { value: "x", enumerable: false }, y: { value: "y", enumerable: true }, }), ); // '{"y":"y"}' // BigInt values throw JSON.stringify({ x: 2n }); // TypeError: BigInt value can't be serialized in JSON ``` ### [Using a function as replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#using_a_function_as_replacer) js ``` function replacer(key, value) { // Filtering out properties if (typeof value === "string") { return undefined; } return value; } const foo = { foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7, }; JSON.stringify(foo, replacer); // '{"week":45,"month":7}' ``` If you wish the `replacer` to distinguish an initial object from a key with an empty string property (since both would give the empty string as key and potentially an object as value), you will have to keep track of the iteration count (if it is beyond the first iteration, it is a genuine empty string key). js ``` function makeReplacer() { let isInitial = true; return (key, value) => { if (isInitial) { isInitial = false; return value; } if (key === "") { // Omit all properties with name "" (except the initial object) return undefined; } return value; }; } const replacer = makeReplacer(); console.log(JSON.stringify({ "": 1, b: 2 }, replacer)); // "{"b":2}" ``` ### [Using an array as replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#using_an_array_as_replacer) js ``` const foo = { foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7, }; JSON.stringify(foo, ["week", "month"]); // '{"week":45,"month":7}', only keep "week" and "month" properties ``` ### [Using the space parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#using_the_space_parameter) Indent the output with one space: js ``` console.log(JSON.stringify({ a: 2 }, null, " ")); /* { "a": 2 } */ ``` Using a tab character mimics standard pretty-print appearance: js ``` console.log(JSON.stringify({ uno: 1, dos: 2 }, null, "\t")); /* { "uno": 1, "dos": 2 } */ ``` ### [toJSON() behavior](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#tojson_behavior) Defining `toJSON()` for an object allows overriding its serialization behavior. js ``` const obj = { data: "data", toJSON(key) { return key ? `Now I am a nested object under key '${key}'` : this; }, }; JSON.stringify(obj); // '{"data":"data"}' JSON.stringify({ obj }); // '{"obj":"Now I am a nested object under key 'obj'"}' JSON.stringify([obj]); // '["Now I am a nested object under key '0'"]' ``` ### [Issue with serializing circular references](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#issue_with_serializing_circular_references) Since the [JSON format](https://www.json.org/) doesn't support object references (although an [IETF draft exists](https://datatracker.ietf.org/doc/html/draft-pbryan-zyp-json-ref-03)), a [`TypeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) will be thrown if one attempts to encode an object with circular references. js ``` const circularReference = {}; circularReference.myself = circularReference; // Serializing circular references throws "TypeError: cyclic object value" JSON.stringify(circularReference); ``` To serialize circular references, you can use a library that supports them (e.g., [cycle.js](https://github.com/douglascrockford/JSON-js/blob/master/cycle.js) by Douglas Crockford) or implement a solution yourself, which will require finding and replacing (or removing) the cyclic references by serializable values. If you are using `JSON.stringify()` to deep-copy an object, you may instead want to use [`structuredClone()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/structuredClone "structuredClone()"), which supports circular references. JavaScript engine APIs for binary serialization, such as [`v8.serialize()`](https://nodejs.org/api/v8.html#v8serializevalue), also support circular references. ### [Using JSON.stringify() with localStorage](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#using_json.stringify_with_localstorage) In a case where you want to store an object created by your user and allow it to be restored even after the browser has been closed, the following example is a model for the applicability of `JSON.stringify()`: js ``` // Creating an example of JSON const session = { screens: [], state: true, }; session.screens.push({ name: "screenA", width: 450, height: 250 }); session.screens.push({ name: "screenB", width: 650, height: 350 }); session.screens.push({ name: "screenC", width: 750, height: 120 }); session.screens.push({ name: "screenD", width: 250, height: 60 }); session.screens.push({ name: "screenE", width: 390, height: 120 }); session.screens.push({ name: "screenF", width: 1240, height: 650 }); // Converting the JSON string with JSON.stringify() // then saving with localStorage in the name of session localStorage.setItem("session", JSON.stringify(session)); // Example of how to transform the String generated through // JSON.stringify() and saved in localStorage in JSON object again const restoredSession = JSON.parse(localStorage.getItem("session")); // Now restoredSession variable contains the object that was saved // in localStorage console.log(restoredSession); ``` ### [Well-formed JSON.stringify()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#well-formed_json.stringify) Engines implementing the [well-formed JSON.stringify specification](https://github.com/tc39/proposal-well-formed-stringify) will stringify lone surrogates (any code point from U+D800 to U+DFFF) using Unicode escape sequences rather than literally (outputting lone surrogates). Before this change, such strings could not be encoded in valid UTF-8 or UTF-16: js ``` JSON.stringify("\uD800"); // '"�"' ``` But with this change `JSON.stringify()` represents lone surrogates using JSON escape sequences that *can* be encoded in valid UTF-8 or UTF-16: js ``` JSON.stringify("\uD800"); // '"\\ud800"' ``` This change should be backwards-compatible as long as you pass the result of `JSON.stringify()` to APIs such as `JSON.parse()` that will accept any valid JSON text, because they will treat Unicode escapes of lone surrogates as identical to the lone surrogates themselves. *Only* if you are directly interpreting the result of `JSON.stringify()` do you need to carefully handle `JSON.stringify()`'s two possible encodings of these code points. ## [Specifications](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#specifications) | Specification | |---| | [ECMAScript® 2027 Language Specification \# sec-json.stringify](https://tc39.es/ecma262/multipage/structured-data.html#sec-json.stringify) | ## [Browser compatibility](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#browser_compatibility) ## [See also](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#see_also) - [Polyfill of modern `JSON.stringify` behavior (symbol, well-formed unicode, raw JSON) in `core-js`](https://github.com/zloirock/core-js#ecmascript-json) - [`JSON.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) - [`JSON.rawJSON()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/rawJSON) ## Help improve MDN [Learn how to contribute](https://developer.mozilla.org/en-US/docs/MDN/Community/Getting_started) This page was last modified on Jul 10, 2025 by [MDN contributors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify/contributors.txt). [View this page on GitHub](https://github.com/mdn/content/blob/main/files/en-us/web/javascript/reference/global_objects/json/stringify/index.md?plain=1 "Folder: en-us/web/javascript/reference/global_objects/json/stringify (Opens in a new tab)") • [Report a problem with this content](https://github.com/mdn/content/issues/new?template=page-report.yml&mdn-url=https%3A%2F%2Fdeveloper.mozilla.org%2Fen-US%2Fdocs%2FWeb%2FJavaScript%2FReference%2FGlobal_Objects%2FJSON%2Fstringify&metadata=%3C%21--+Do+not+make+changes+below+this+line+--%3E%0A%3Cdetails%3E%0A%3Csummary%3EPage+report+details%3C%2Fsummary%3E%0A%0A*+Folder%3A+%60en-us%2Fweb%2Fjavascript%2Freference%2Fglobal_objects%2Fjson%2Fstringify%60%0A*+MDN+URL%3A+https%3A%2F%2Fdeveloper.mozilla.org%2Fen-US%2Fdocs%2FWeb%2FJavaScript%2FReference%2FGlobal_Objects%2FJSON%2Fstringify%0A*+GitHub+URL%3A+https%3A%2F%2Fgithub.com%2Fmdn%2Fcontent%2Fblob%2Fmain%2Ffiles%2Fen-us%2Fweb%2Fjavascript%2Freference%2Fglobal_objects%2Fjson%2Fstringify%2Findex.md%0A*+Last+commit%3A+https%3A%2F%2Fgithub.com%2Fmdn%2Fcontent%2Fcommit%2F544b843570cb08d1474cfc5ec03ffb9f4edc0166%0A*+Document+last+modified%3A+2025-07-10T09%3A07%3A55.000Z%0A%0A%3C%2Fdetails%3E "This will take you to GitHub to file a new issue.") 1. [Standard built-in objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects) 2. [`JSON`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON) 3. Static methods 1. [`isRawJSON()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/isRawJSON) 2. [`parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) 3. [`rawJSON()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/rawJSON) 4. *[`stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)* Your blueprint for a better internet. MDN - [About](https://developer.mozilla.org/en-US/about) - [Blog](https://developer.mozilla.org/en-US/blog/) - [Mozilla careers](https://www.mozilla.org/en-US/careers/listings/) - [Advertise with us](https://developer.mozilla.org/en-US/advertising) - [MDN Plus](https://developer.mozilla.org/en-US/plus) - [Product help](https://support.mozilla.org/products/mdn-plus) Contribute - [MDN Community](https://developer.mozilla.org/en-US/community) - [Community resources](https://developer.mozilla.org/en-US/docs/MDN/Community) - [Writing guidelines](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines) - [MDN Discord](https://developer.mozilla.org/discord) - [MDN on GitHub](https://github.com/mdn) Developers - [Web technologies](https://developer.mozilla.org/en-US/docs/Web) - [Learn web development](https://developer.mozilla.org/en-US/docs/Learn_web_development) - [Guides](https://developer.mozilla.org/en-US/docs/MDN/Guides) - [Tutorials](https://developer.mozilla.org/en-US/docs/MDN/Tutorials) - [Glossary](https://developer.mozilla.org/en-US/docs/Glossary) - [Hacks blog](https://hacks.mozilla.org/) - [Website Privacy Notice](https://www.mozilla.org/privacy/websites/) - [Telemetry Settings](https://www.mozilla.org/en-US/privacy/websites/data-preferences/) - [Legal](https://www.mozilla.org/about/legal/terms/mozilla) - [Community Participation Guidelines](https://www.mozilla.org/about/governance/policies/participation/) Visit [Mozilla Corporation’s](https://www.mozilla.org/) not-for-profit parent, the [Mozilla Foundation](https://foundation.mozilla.org/). Portions of this content are ©1998–2026 by individual mozilla.org contributors. Content available under [a Creative Commons license](https://developer.mozilla.org/docs/MDN/Writing_guidelines/Attrib_copyright_license).
Readable Markdown
## [Try it](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#try_it) ``` console.log(JSON.stringify({ x: 5, y: 6 })); // Expected output: '{"x":5,"y":6}' console.log( JSON.stringify([new Number(3), new String("false"), new Boolean(false)]), ); // Expected output: '[3,"false",false]' console.log(JSON.stringify({ x: [10, undefined, function () {}, Symbol("")] })); // Expected output: '{"x":[10,null,null,null]}' console.log(JSON.stringify(new Date(2006, 0, 2, 15, 4, 5))); // Expected output: '"2006-01-02T15:04:05.000Z"' ``` ## [Syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#syntax) js ``` JSON.stringify(value) JSON.stringify(value, replacer) JSON.stringify(value, replacer, space) ``` ### [Parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#parameters) [`value`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#value) The value to convert to a JSON string. [`replacer` Optional](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#replacer) A function that alters the behavior of the stringification process, or an array of strings and numbers that specifies properties of `value` to be included in the output. If `replacer` is an array, all elements in this array that are not strings or numbers (either primitives or wrapper objects), including [`Symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) values, are completely ignored. If `replacer` is anything other than a function or an array (e.g., [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/null) or not provided), all string-keyed properties of the object are included in the resulting JSON string. [`space` Optional](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#space) A string or number that's used to insert white space (including indentation, line break characters, etc.) into the output JSON string for readability purposes. If this is a number, it indicates the number of space characters to be used as indentation, clamped to 10 (that is, any number greater than `10` is treated as if it were `10`). Values less than 1 indicate that no space should be used. If this is a string, the string (or the first 10 characters of the string, if it's longer than that) is inserted before every nested object or array. If `space` is anything other than a string or number (can be either a primitive or a wrapper object) — for example, is [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/null) or not provided — no white space is used. ### [Return value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#return_value) A JSON string representing the given value, or undefined. ### [Exceptions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#exceptions) [`TypeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) Thrown in one of the following cases: - `value` contains a circular reference. - A [`BigInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) value is encountered. ## [Description](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#description) `JSON.stringify()` converts a value to the JSON notation that the value represents. Values are stringified in the following manner: - [`Boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean), [`Number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number), [`String`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String), and [`BigInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) (obtainable via [`Object()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) objects are converted to the corresponding primitive values during stringification, in accordance with the traditional conversion semantics. [`Symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) objects (obtainable via [`Object()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) are treated as plain objects. - Attempting to serialize [`BigInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) values will throw. However, if the BigInt has a `toJSON()` method (through monkey patching: `BigInt.prototype.toJSON = ...`), that method can provide the serialization result. This constraint ensures that a proper serialization (and, very likely, its accompanying deserialization) behavior is always explicitly provided by the user. - [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined), [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function), and [`Symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) values are not valid JSON values. If any such values are encountered during conversion, they are either omitted (when found in an object) or changed to [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/null) (when found in an array). `JSON.stringify()` can return `undefined` when passing in "pure" values like `JSON.stringify(() => {})` or `JSON.stringify(undefined)`. - The numbers [`Infinity`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Infinity) and [`NaN`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN), as well as the value [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/null), are all considered `null`. (But unlike the values in the previous point, they would never be omitted.) - Arrays are serialized as arrays (enclosed by square brackets). Only array indices between 0 and `length - 1` (inclusive) are serialized; other properties are ignored. - The special raw JSON object created with [`JSON.rawJSON()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/rawJSON) is serialized as the raw JSON text it contains (by accessing its `rawJSON` property). - For other objects: - All [`Symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol)\-keyed properties will be completely ignored, even when using the [`replacer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_replacer_parameter) parameter. - If the value has a `toJSON()` method, it's responsible to define what data will be serialized. Instead of the object being serialized, the value returned by the `toJSON()` method when called will be serialized. `JSON.stringify()` calls `toJSON` with one parameter, the `key`, which has the same semantic as the `key` parameter of the [`replacer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_replacer_parameter) function: - if this object is a property value, the property name - if it is in an array, the index in the array, as a string - if `JSON.stringify()` was directly called on this object, an empty string All [`Temporal`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal) objects implement the `toJSON()` method, which returns a string (the same as calling `toString()`). Thus, they will be serialized as strings. Similarly, [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) objects implement `toJSON()`, which returns the same as [`toISOString()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString). - Only [enumerable own properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Enumerability_and_ownership_of_properties) are visited. This means [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map), [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set), etc. will become `"{}"`. You can use the [`replacer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_replacer_parameter) parameter to serialize them to something more useful. Properties are visited using the same algorithm as [`Object.keys()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys), which has a well-defined order and is stable across implementations. For example, `JSON.stringify` on the same object will always produce the same string, and `JSON.parse(JSON.stringify(obj))` would produce an object with the same key ordering as the original (assuming the object is completely JSON-serializable). ### [The replacer parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_replacer_parameter) The `replacer` parameter can be either a function or an array. As an array, its elements indicate the names of the properties in the object that should be included in the resulting JSON string. Only string and number values are taken into account; symbol keys are ignored. As a function, it takes two parameters: the `key` and the `value` being stringified. The object in which the key was found is provided as the `replacer`'s `this` context. The `replacer` function is called for the initial object being stringified as well, in which case the `key` is an empty string (`""`). It is then called for each property on the object or array being stringified. Array indices will be provided in its string form as `key`. The current property value will be replaced with the `replacer`'s return value for stringification. This means: - If you return a number, string, boolean, or `null`, that value is directly serialized and used as the property's value. (Returning a BigInt will throw as well.) - If you return a [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function), [`Symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol), or [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined), the property is not included in the output. - If you return any other object, the object is recursively stringified, calling the `replacer` function on each property. **Note:** When parsing JSON generated with `replacer` functions, you would likely want to use the [`reviver`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#using_the_reviver_parameter) parameter to perform the reverse operation. Typically, array elements' index would never shift (even when the element is an invalid value like a function, it will become `null` instead of omitted). Using the `replacer` function allows you to control the order of the array elements by returning a different array. ### [The space parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_space_parameter) The `space` parameter may be used to control spacing in the final string. - If it is a number, successive levels in the stringification will each be indented by this many space characters. - If it is a string, successive levels will be indented by this string. Each level of indentation will never be longer than 10. Number values of `space` are clamped to 10, and string values are truncated to 10 characters. ## [Examples](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#examples) ### [Using JSON.stringify](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#using_json.stringify) js ``` JSON.stringify({}); // '{}' JSON.stringify(true); // 'true' JSON.stringify("foo"); // '"foo"' JSON.stringify([1, "false", false]); // '[1,"false",false]' JSON.stringify([NaN, null, Infinity]); // '[null,null,null]' JSON.stringify({ x: 5 }); // '{"x":5}' JSON.stringify(new Date(1906, 0, 2, 15, 4, 5)); // '"1906-01-02T15:04:05.000Z"' JSON.stringify({ x: 5, y: 6 }); // '{"x":5,"y":6}' JSON.stringify([new Number(3), new String("false"), new Boolean(false)]); // '[3,"false",false]' // String-keyed array elements are not enumerable and make no sense in JSON const a = ["foo", "bar"]; a["baz"] = "quux"; // a: [ 0: 'foo', 1: 'bar', baz: 'quux' ] JSON.stringify(a); // '["foo","bar"]' JSON.stringify({ x: [10, undefined, function () {}, Symbol("")] }); // '{"x":[10,null,null,null]}' // Standard data structures JSON.stringify([ new Set([1]), new Map([[1, 2]]), new WeakSet([{ a: 1 }]), new WeakMap([[{ a: 1 }, 2]]), ]); // '[{},{},{},{}]' // TypedArray JSON.stringify([new Int8Array([1]), new Int16Array([1]), new Int32Array([1])]); // '[{"0":1},{"0":1},{"0":1}]' JSON.stringify([ new Uint8Array([1]), new Uint8ClampedArray([1]), new Uint16Array([1]), new Uint32Array([1]), ]); // '[{"0":1},{"0":1},{"0":1},{"0":1}]' JSON.stringify([new Float32Array([1]), new Float64Array([1])]); // '[{"0":1},{"0":1}]' // toJSON() JSON.stringify({ x: 5, y: 6, toJSON() { return this.x + this.y; }, }); // '11' // Symbols: JSON.stringify({ x: undefined, y: Object, z: Symbol("") }); // '{}' JSON.stringify({ [Symbol("foo")]: "foo" }); // '{}' JSON.stringify({ [Symbol.for("foo")]: "foo" }, [Symbol.for("foo")]); // '{}' JSON.stringify({ [Symbol.for("foo")]: "foo" }, (k, v) => { if (typeof k === "symbol") { return "a symbol"; } }); // undefined // Non-enumerable properties: JSON.stringify( Object.create(null, { x: { value: "x", enumerable: false }, y: { value: "y", enumerable: true }, }), ); // '{"y":"y"}' // BigInt values throw JSON.stringify({ x: 2n }); // TypeError: BigInt value can't be serialized in JSON ``` ### [Using a function as replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#using_a_function_as_replacer) js ``` function replacer(key, value) { // Filtering out properties if (typeof value === "string") { return undefined; } return value; } const foo = { foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7, }; JSON.stringify(foo, replacer); // '{"week":45,"month":7}' ``` If you wish the `replacer` to distinguish an initial object from a key with an empty string property (since both would give the empty string as key and potentially an object as value), you will have to keep track of the iteration count (if it is beyond the first iteration, it is a genuine empty string key). js ``` function makeReplacer() { let isInitial = true; return (key, value) => { if (isInitial) { isInitial = false; return value; } if (key === "") { // Omit all properties with name "" (except the initial object) return undefined; } return value; }; } const replacer = makeReplacer(); console.log(JSON.stringify({ "": 1, b: 2 }, replacer)); // "{"b":2}" ``` ### [Using an array as replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#using_an_array_as_replacer) js ``` const foo = { foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7, }; JSON.stringify(foo, ["week", "month"]); // '{"week":45,"month":7}', only keep "week" and "month" properties ``` ### [Using the space parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#using_the_space_parameter) Indent the output with one space: js ``` console.log(JSON.stringify({ a: 2 }, null, " ")); /* { "a": 2 } */ ``` Using a tab character mimics standard pretty-print appearance: js ``` console.log(JSON.stringify({ uno: 1, dos: 2 }, null, "\t")); /* { "uno": 1, "dos": 2 } */ ``` ### [toJSON() behavior](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#tojson_behavior) Defining `toJSON()` for an object allows overriding its serialization behavior. js ``` const obj = { data: "data", toJSON(key) { return key ? `Now I am a nested object under key '${key}'` : this; }, }; JSON.stringify(obj); // '{"data":"data"}' JSON.stringify({ obj }); // '{"obj":"Now I am a nested object under key 'obj'"}' JSON.stringify([obj]); // '["Now I am a nested object under key '0'"]' ``` ### [Issue with serializing circular references](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#issue_with_serializing_circular_references) Since the [JSON format](https://www.json.org/) doesn't support object references (although an [IETF draft exists](https://datatracker.ietf.org/doc/html/draft-pbryan-zyp-json-ref-03)), a [`TypeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) will be thrown if one attempts to encode an object with circular references. js ``` const circularReference = {}; circularReference.myself = circularReference; // Serializing circular references throws "TypeError: cyclic object value" JSON.stringify(circularReference); ``` To serialize circular references, you can use a library that supports them (e.g., [cycle.js](https://github.com/douglascrockford/JSON-js/blob/master/cycle.js) by Douglas Crockford) or implement a solution yourself, which will require finding and replacing (or removing) the cyclic references by serializable values. If you are using `JSON.stringify()` to deep-copy an object, you may instead want to use [`structuredClone()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/structuredClone "structuredClone()"), which supports circular references. JavaScript engine APIs for binary serialization, such as [`v8.serialize()`](https://nodejs.org/api/v8.html#v8serializevalue), also support circular references. ### [Using JSON.stringify() with localStorage](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#using_json.stringify_with_localstorage) In a case where you want to store an object created by your user and allow it to be restored even after the browser has been closed, the following example is a model for the applicability of `JSON.stringify()`: js ``` // Creating an example of JSON const session = { screens: [], state: true, }; session.screens.push({ name: "screenA", width: 450, height: 250 }); session.screens.push({ name: "screenB", width: 650, height: 350 }); session.screens.push({ name: "screenC", width: 750, height: 120 }); session.screens.push({ name: "screenD", width: 250, height: 60 }); session.screens.push({ name: "screenE", width: 390, height: 120 }); session.screens.push({ name: "screenF", width: 1240, height: 650 }); // Converting the JSON string with JSON.stringify() // then saving with localStorage in the name of session localStorage.setItem("session", JSON.stringify(session)); // Example of how to transform the String generated through // JSON.stringify() and saved in localStorage in JSON object again const restoredSession = JSON.parse(localStorage.getItem("session")); // Now restoredSession variable contains the object that was saved // in localStorage console.log(restoredSession); ``` ### [Well-formed JSON.stringify()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#well-formed_json.stringify) Engines implementing the [well-formed JSON.stringify specification](https://github.com/tc39/proposal-well-formed-stringify) will stringify lone surrogates (any code point from U+D800 to U+DFFF) using Unicode escape sequences rather than literally (outputting lone surrogates). Before this change, such strings could not be encoded in valid UTF-8 or UTF-16: js ``` JSON.stringify("\uD800"); // '"�"' ``` But with this change `JSON.stringify()` represents lone surrogates using JSON escape sequences that *can* be encoded in valid UTF-8 or UTF-16: js ``` JSON.stringify("\uD800"); // '"\\ud800"' ``` This change should be backwards-compatible as long as you pass the result of `JSON.stringify()` to APIs such as `JSON.parse()` that will accept any valid JSON text, because they will treat Unicode escapes of lone surrogates as identical to the lone surrogates themselves. *Only* if you are directly interpreting the result of `JSON.stringify()` do you need to carefully handle `JSON.stringify()`'s two possible encodings of these code points. ## [Specifications](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#specifications) | Specification | |---| | [ECMAScript® 2027 Language Specification \# sec-json.stringify](https://tc39.es/ecma262/multipage/structured-data.html#sec-json.stringify) | ## [Browser compatibility](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#browser_compatibility) ## [See also](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#see_also) - [Polyfill of modern `JSON.stringify` behavior (symbol, well-formed unicode, raw JSON) in `core-js`](https://github.com/zloirock/core-js#ecmascript-json) - [`JSON.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) - [`JSON.rawJSON()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/rawJSON)
Shard53 (laksa)
Root Hash7082249407640205653
Unparsed URLorg,mozilla!developer,/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify s443