JSON5: JSON with comments (and more!)

Oct 8, 2022 17:00 · 231 words · 2 minute read

JSON gets used for a lot of different use cases. One of it: Config files. For example, you can configure the code editor VS Code via a settings.json config file.

One downside: The original JSON specification disallows comments. But comments are very useful - for example, you could note why you have selected a specific config value, or write down alternative config values. VS Code allows comments in its config files - it calls this format “JSON with comments”, or jsonc mode. You can enable jsonc mode for any file. Therefore, writing JSON with comments is a solved problem.

But: As an application developer - how do you parse such a JSON file with comments, like VS Code does? There is the jsonc-parser library for Node.js by Microsoft themselves, the developers of VS Code.

But it turns out, there is even a better option! Meet JSON5, a JSON extension, that extends JSON not just with comments, but other useful syntactic features (e.g. trailing commas are allowed, strings may be single-quoted). Features that are already allowed in the JavaScript/ECMAScript object notation, but not in the original JSON format.

The most popular JSON5 parser is also one for Node.js, with over 5k stars - but there exist implementations for other languages as well. E.g. for Golang and Rust.

Might be useful for projects where you want to allow configuration via JSON files! 💡