Using JSON in Modern C++

Adding comments to JSON

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

Abstract art representing computer programming

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.

Answers to questions are automatically generated and may not have been reviewed.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved