JSON (JavaScript Object Notation) is a lightweight data format that is commonly used for transmitting data.
However, one limitation of JSON is that it has no official support for comments.
Why Doesn't JSON Support Comments?
JSON was designed to be a lightweight data interchange format, focused on representing structured data in a universal way.
When it was first created, several design decisions were made:
The creators opted to only include the minimum viable set of data types - objects, arrays, primitives.
Comments were excluded for a few key reasons:
So in summary, the minimalist design goals of JSON led to comments being excluded from the spec. The use cases JSON solves (universal data interchange) don't require comments.
Other formats like YAML or XML can be used if commenting is a must. And workarounds allow annotating JSON-like data with comments when needed.
Here are some creative ways to add comments to JSON:
Using Key/Value Pairs
We can add a key with a string value to embed a comment:
{
"name": "John",
"age": 30,
"_comment": "This is a comment"
}
Just add an underscore before the key name to indicate it's a comment.
Trailing Commas
Adding a trailing comma after the last item also allows commenting on that line:
{
"name": "John",
"age": 30, // This is a comment
}
Use JavaScript Comments
Since JSON is based on JavaScript syntax, we can use JS comment styles:
/* Multi-line
comment */
{
"name": "John",
// Single-line comment
}
The comments won't be part of the JSON, but can help annotate it.
Separate Comment Files
Keep comments in a separate JSON file that gets loaded alongside the raw data.
Online/Visual Editors
Many online/visual JSON editors will preserve comments in the JSON file.
So in summary, while JSON has no native comment support, the above methods allow annotating JSON data with comments to provide context and clarity.
JSONC
JSONC is an emerging standard that formally introduces comments to JSON.
It allows comments with either
{
"name": "John",
// This is a comment
"age": 30
}
JSONC files can be parsed by JSONC parsers to extract the comments.
Support for JSONC is still limited, but growing. It provides a standard way forward for officially supporting comments in JSON.
So in the future, we may be able to annotate JSON files directly using JSONC syntax. But for now, the earlier methods allow us to embed comments without breaking standard JSON parsers.