JSON.stringify() is a JavaScript method that converts a JavaScript value—such as an object, array, or primitive—into a JSON-formatted string. It is commonly used for serializing data for storage, transmission, or debugging.
Key Features
Basic Usage:
JSON.stringify({ name: "Alice", age: 30 }); // Returns: '{"name":"Alice","age":30}'Supports Arrays and Nested Objects:
JSON.stringify([1, "hello", { nested: true }]); // Returns: '[1,"hello",{"nested":true}]'Handles Special Values:
undefined,function, andSymbolvalues are omitted from objects or converted tonullin arrays.null,Infinity, andNaNare converted tonull.Dateobjects are converted to ISO strings (e.g.,"2026-02-04T00:00:00.000Z").BigIntvalues throw a TypeError unless atoJSON()method is defined.
Replacer Parameter:
Allows filtering or transforming values during stringification:JSON.stringify({ a: 1, b: 2 }, (key, value) => { return key === 'a' ? undefined : value; }); // Returns: '{"b":2}'Space Parameter (Pretty-Print):
Adds indentation for readability:JSON.stringify({ a: 1, b: 2 }, null, 2); // Returns: // { // "a": 1, // "b": 2 // }
Limitations
Circular References: Throws a
TypeErrorif the object contains self-references.Unsupported Types:
Map,Set,WeakMap,WeakSet, andErrorobjects are converted to{}.No Built-in Support for Custom Types: Requires manual handling via
toJSON()or external libraries.
Common Use Cases
Sending data to APIs.
Storing data in
localStorage.Debugging complex objects.
Converting JavaScript data to a transportable format.
Note: For deep cloning with circular references, consider using
structuredClone()instead ofJSON.stringify()andJSON.parse().
There is a way to serialize a function in JS, but you'll have to eval it on the other side and it will also lose access to it's original scope. A way to do it would be:
CopyJSON.stringify(objWithFunction, function(key, val) {
if (typeof val === 'function') {
return val + ''; // implicitly `toString` it
}
return val;
});
There are some legitimate uses for what you're asking despite what people are posting here, however, it all depends on what you're going to be using this for. There may be a better way of going about whatever it is you're trying to do.
Answer from chjj on Stack OverflowJSON.stringify function
JSON stringify a Set
JSON stringify objects with json strings already as values
[AskJS] PETITION: Make JSON.stringify use any object's toString method internally!
Videos
» npm install fast-json-stringify
There is a way to serialize a function in JS, but you'll have to eval it on the other side and it will also lose access to it's original scope. A way to do it would be:
CopyJSON.stringify(objWithFunction, function(key, val) {
if (typeof val === 'function') {
return val + ''; // implicitly `toString` it
}
return val;
});
There are some legitimate uses for what you're asking despite what people are posting here, however, it all depends on what you're going to be using this for. There may be a better way of going about whatever it is you're trying to do.
In fact, It's very easy to serealize / parse javascript object with methods.
Take a look at JSONfn plugin.
http://www.eslinstructor.net/jsonfn/
JSON.stringify doesn't directly work with sets because the data stored in the set is not stored as properties.
But you can convert the set to an array. Then you will be able to stringify it properly.
Any of the following will do the trick:
JSON.stringify([...s]);
JSON.stringify([...s.keys()]);
JSON.stringify([...s.values()]);
JSON.stringify(Array.from(s));
JSON.stringify(Array.from(s.keys()));
JSON.stringify(Array.from(s.values()));
You can pass a "replacer" function to JSON.stringify:
const fooBar = {
foo: new Set([1, 2, 3]),
bar: new Set([4, 5, 6])
};
JSON.stringify(
fooBar,
(_key, value) => (value instanceof Set ? [...value] : value)
);
Result:
"{"foo":[1,2,3],"bar":[4,5,6]}"
toJSON is a legacy artifact, and a better approach is to use a custom replacer, see https://github.com/DavidBruant/Map-Set.prototype.toJSON/issues/16
Assuming you don't know which properties are JSON, you could use the replacer function parameter on JSON.stringify to check if a value is a JSON string. The below example tries to parse each string inside a try..catch , so is not the most efficient, but should do the trick (on nested properties as well)
var obj = {id:1, options:"{\"code\":3,\"type\":\"AES\"}"};
function checkVal(key,val){
if(typeof val === 'string'){
try{return JSON.parse(val);}catch(e){}
}
return val;
}
var res = JSON.stringify(obj,checkVal);
console.log('normal output', JSON.stringify(obj))
console.log('with replacer', res);
No, you can't do that.
If you did not encode that string, JSON.parse will not return a correct string.
The cleanest solution to do that is use JSON for obj.options, and stringify it when you need to use it.
What do you guys think? Should I make an official proposal? What would be the best way to make such spec proposal?
And tell me what you think! The idea is for any object's toString method override the way JSON.stringify creates the string. For example:
var vec =
{
x: 0,
y: 0,
toString() => `[${this.x},${this.y}]`
}
JSON.stringify(vec) //will return: '[0,0]'This way I won't need to use a custom stream to alter a big object when converting it to JSON!
Or would you say this is very unnecessary, even if an easy thing to add to JS?
You need to JSON.parse() your valid JSON string.
var str = '{"hello":"world"}';
try {
var obj = JSON.parse(str); // this is how you parse a string into JSON
document.body.innerHTML += obj.hello;
} catch (ex) {
console.error(ex);
}
JSON.parse is the opposite of JSON.stringify.