Can I use comments inside a JSON file? If so, how?
You should write a JSON schema instead. JSON schema is currently a proposed Internet draft specification. Besides documentation, the schema can also be used for validating your JSON data.
Example:
{
"description":"A person",
"type":"object",
"properties":
{
"name":
{
"type":"string"
},
"age":
{
"type":"integer",
"maximum":125
}
}
}
You can provide documentation by using the description schema attribute.
It depends on your JSON library. Json.NET supports JavaScript-style comments, /* commment */
.
See another Stack Overflow question.
The Dojo Toolkit JavaScript toolkit (at least as of version 1.4), allows you to include comments in your JSON. The comments can be of /* */
format. Dojo Toolkit consumes the JSON via the dojo.xhrGet()
call.
Other JavaScript toolkits may work similarly.
This can be helpful when experimenting with alternate data structures (or even data lists) before choosing a final option.
Comments are not an official standard, although some parsers support C++-style comments. One that I use is JsonCpp. In the examples there is this one:
// Configuration options
{
// Default encoding for text
"encoding" : "UTF-8",
// Plug-ins loaded at start-up
"plug-ins" : [
"python",
"c++",
"ruby"
],
// Tab indent size
"indent" : { "length" : 3, "use_space": true }
}
jsonlint does not validate this. So comments are a parser specific extension and not standard.
Another parser is JSON5.
An alternative to JSON TOML.
A further alternative is jsonc.
The latest version of nlohmann/json has optional support for ignoring comments on parsing.
In my case, I need to use comments for debug purposes right before the output of the JSON structure. So I decided to use debug information in the HTTP header, to avoid breaking the client:
header("My-Json-Comment: Yes, I know it's a workaround ;-) ");
To cut a JSON item into parts I add "dummy comment" lines:
{
"#############################" : "Part1",
"data1" : "value1",
"data2" : "value2",
"#############################" : "Part2",
"data4" : "value3",
"data3" : "value4"
}