The JSON specification does not include any provision for comments. So a standard JSON parser will throw an error if you try to include comments like you would in a language like C++:
{
"name": "Paladin",
"level": 10, // current level, default is 1
"health": 100 /* starting health */
}
This is not valid JSON and will cause a parse error.
Unlike some other data formats like XML or YAML, JSON does not have any official syntax for comments. The nlohmann::json
library, following the JSON specification, does not support comments either.
If you try to parse a JSON string containing comments with the nlohmann::json
library, you'll get a parse error:
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main() {
std::string data = R"({
"name": "Paladin", // character class
"level": 10, // current level
"health": 100 /* starting health */
})";
try {
json j = json::parse(data);
} catch (json::parse_error& e) {
std::cout << "parse error: " << e.what()
<< std::endl;
}
}
parse error: [json.exception.parse_error.101] parse error at line 2, column 24: syntax error while parsing object key - invalid literal; last read: '"Paladin", /'; expected string literal
So if you want to include comments or other metadata in your JSON files, you'll need to find another way to do it. Some options include:
In general, it's best to keep your JSON files clean and use external documentation if necessary. JSON is meant to be a simple, lightweight data interchange format, not a self-documenting file format.
Answers to questions are automatically generated and may not have been reviewed.
A practical guide to working with the JSON data format in C++ using the popular nlohmann::json
library.