CodeBlanks Logo Icon CodeBlanks

JSON library

Learn JSON serialization with nlohmann/json.

What is nlohmann/json?

nlohmann/json is a popular header only JSON library for C++. You use it with a single #include <nlohmann/json.hpp>. JSON objects are represented by the nlohmann::json type; fields are added as j["key"] = value;.

Example: nlohmann::json j; j["name"] = "Alex"; j["age"] = 30;. You add to an array with j["tags"] = {"a", "b"};. The j.dump() method returns the JSON as a string. j.parse(str) builds a JSON object from a string. This library offers a more structured way than text serialization.

Creating JSON and dump

After creating a nlohmann::json object you add fields with square brackets. The j.dump() method returns the JSON as a compact string. j.dump(2) produces a readable, 2 space indented string.

Example: nlohmann::json j; j["name"] = "Alex"; j["age"] = 30; std::cout << j.dump();. Output: {"age":30,"name":"Alex"}. Keys are sorted alphabetically because the library uses std::map by default. To read a field, j["name"] is enough; the return type is deduced. This is safer than text serialization for structured data.

Practice Create a JSON object and print it

Add #include <nlohmann/json.hpp>. Define nlohmann::json j;. Set j["name"] = "Alex"; and j["age"] = 30;. Print with std::cout << j.dump();.

Starter code

main.cpp
#include <iostream>
#include <string>

// Add the nlohmann/json header and JSON object

int main() {
    // Create JSON and print it
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <nlohmann/json.hpp>

int main() {
    nlohmann::json j;
    j["name"] = "Alex";
    j["age"] = 30;
    std::cout << j.dump();
    return 0;
}

Expected output

{"age":30,"name":"Alex"}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How is nlohmann/json included?

  • #include <json>
  • #include <std::json>
  • #include <nlohmann/json.hpp> Correct answer
  • #include <json/json.h>

Explanation: #include <nlohmann/json.hpp> enables the library with one header.

2 Complete the JSON type

Question
____ j;
Answer
nlohmann::json j;

Explanation: nlohmann::json defines a JSON object.

3 Match each piece to its role

Term Meaning
j["name"] = "Alex" Adds a field
j.dump() Produces a string
j.dump(2) Produces indented string
nlohmann::json JSON type

All lessons in Advanced