JSON.stringify takes more optional arguments.
Try:
JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab
From:
How can I beautify JSON programmatically?
It should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre> tag to get newlines to show.
JavaScript: How can I generate formatted easy-to-read JSON straight from an object? - Stack Overflow
javascript - JSON.stringify function - Stack Overflow
javascript - JSON stringify a Set - Stack Overflow
[AskJS] PETITION: Make JSON.stringify use any object's toString method internally!
Videos
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:
JSON.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
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?