Pretty-printing JSON

How can I print out JSON in a nicely formatted way?

By default, when you output a JSON object to a stream, it will be compact with minimal whitespace:

#include <iostream>
#include <json.hpp>
using json = nlohmann::json;

int main() {
  using namespace nlohmann::literals;
  json doc = {R"(
    {
      "name": "Barbarian",
      "health": 100,
      "equipment": ["axe", "helmet"]
    }
  )"_json};

  std::cout << doc;
}
{"equipment":["axe","helmet"],"health":100,"name":"Barbarian"}

To print out the JSON in a more human-readable format with newlines and indentation, you can use the dump() method and pass it an integer indicating how many spaces to use per indentation level:

#include <iostream>
#include <json.hpp>
using json = nlohmann::json;

int main() {
  using namespace nlohmann::literals;
  json doc = {R"(
    {
      "name": "Barbarian",
      "health": 100,
      "equipment": ["axe", "helmet"]
    }
  )"_json};

  std::cout << doc.dump(2);
}
{
  "equipment": [
    "axe",
    "helmet"
  ],
  "health": 100,
  "name": "Barbarian"
}

Now the JSON is much easier to read, with each object on its own line and arrays and nested objects indented.

You can adjust the indentation by changing the argument to dump(). 2 and 4 spaces are common conventions.

Keep in mind this "pretty-printed" format is much easier for humans to read, but it does take up more space than the compact representation. So for things like transmitting JSON over a network or storing it, you'll generally want to keep it compact. The "pretty-printed" format is great for debugging and logging though.

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?
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?
Adding comments to JSON
Can I add comments to a JSON file to document what certain parts mean?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant