Make `JSON.stringify` more convenient?

As we all know, JSON.stringify has accepted the second parameters as replacer, while the third one as space. Recently I found that it is not convenient for me to add spaces for only certain levels of an object during stringifying like:

Converting this

{
    a : 1,
    b : {
        c : 1,
    }
}

To

{
    "a": 1,
    "b": {"c":1}
}

It may be more convenient for the third parameters space to be defined as a handler function like replacer:

JSON.stringify({
    a : 1,
    b : {
        c : 1,
    }
}, null, key => key === 'b' ? 0 : 4); 

I don't think this is a sufficiently common thing for people to care about that it warrants support in the language.

3 Likes

It's helpful for constructing JavaScript files.

Current version:

var obj = {
	a : 1,
	b : {
		c : 1,
	}
};

fs.writeFileSync('test.js', `
module.exports = ${JSON.stringify(obj, (k, v) => k === 'b' ? JSON.stringify(v, null, 0) : v, 4)
	.replace(/\\"/g, '"')
	.replace(/"{/g, '{')
	.replace(/}"/g, '}')};
`, {encoding: 'utf8'});

After that proposal:

fs.writeFileSync('test.js', `
module.exports = ${JSON.stringify(obj, null, key => key === 'b' ? 0 : 4)};
`, {encoding: 'utf8'});

That seems like something you'd want to use an actual parser on - eslint, babel, something like that.

1 Like

I would strongly advise the use of a tool like prettier for pretty-printing JavaScript files, and that you construct them using estree or shift-ast or something rather than mashing strings together. JSON.stringify is very much not intended for that purpose and I do not think the committee will be receptive to feature suggestions aimed at that use case.

1 Like

I know there are few libraries for modifying JavaScript files directly, and developers always like to use JSON files to store objects because it is easily serialized. However, JSON files sometimes have their disadvantages like unable to comment, dynamic export, etc. It is just a suggestion since that JSON.stringify has provided space for prettifying.

This kind of logic in the language will create a lot of additional overhead for very little value. If you wish to format your JSON, there are many different libraries that allow for this, and you can include/use them.

edit: You may also wish to look into YAML or TOML, both of which imho are slightly more readable. Also, to my knowledge a lot of formatters/libraries won't preserve comments, not sure about JSON5.

1 Like