Adding comments to JSON

Can I add comments to a JSON file to document what certain parts mean?

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:

  1. Put the comments in a separate file or in your code as string literals.
  2. Use a different data format that supports comments, like YAML or TOML.
  3. Embed the comments as actual string values in your JSON (but this clutters your data).

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.

Using JSON in Modern C++

A practical guide to working with the JSON data format in C++ using the popular nlohmann::json library.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Creating a JSON object from a file
How can I create a JSON object by reading the contents of a JSON file?
Checking if a key exists in JSON
What is the best way to check if a specific key exists in a JSON object?
Pretty-printing JSON
How can I print out JSON in a nicely formatted way?
Serializing private class members to JSON
How can I serialize private members of a class to JSON?
Using custom types as JSON keys
Can I use a custom type as a key in a JSON object?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant