Using JSON in Modern C++

Pretty-printing JSON

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

Abstract art representing computer programming

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.

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