Currently, the JSON
global object contains the methods parse
and stringify
in order to, respectively, parse JSON strings to ordinary JavaScript values, and serialize JavaScript values to JSON strings. Alas, both these methods are synchronous, which is bad if they’re used on the main thread. Although usually very fast, for larger objects they could take hundreds of milliseconds to do their jobs (e.g. parsing a string larger than 1 MB).
My proposal would be to introduce two other methods, parseAsync
and stringifyAsync
(tentative names), with the same signatures of parse
and stringify
respectively, but returning a Promise
of the expected type. For example:
const data = JSON.parse(rawJSON);
// would become
JSON.parseAsync(rawJSON).then(data => { ... });
const payload = JSON.stringify(data);
// would become
JSON.stringifyAsync(data).then(payload => { ... });
I think this could be valuable especially on a Node-based server, where avoiding to block the main thread is paramount.
These new methods would go well for an eventual, future streaming JSON parsing and serializing API.