Introduction to nlohmann/json: JSON for Modern C++
Emily Parker
Product Engineer · Leapcell
Key Takeaways
-
nlohmann/jsonis a header-only C++ library for easy JSON handling. - It integrates naturally with STL and modern C++ features.
-
Custom type serialization is supported via
to_jsonandfrom_json. - Header-only Library : No need for separate compilation; simply include the header file in your project.
- Modern C++ Integration : Utilizes C++11 features, such as initializer lists, type inference, and range-based loops.
-
STL Compatibility
: Works seamlessly with STL containers like
std::vector,std::map, andstd::unordered_map. - Serialization Support : Easily convert between JSON and custom C++ types.
- Comprehensive Documentation : Extensive examples and API references are available to assist developers.
- Develop with Node.js, Python, Go, or Rust.
- pay only for usage — no requests, no charges.
- Pay-as-you-go with no idle charges.
- Example: $25 supports 6.94M requests at a 60ms average response time.
- Intuitive UI for effortless setup.
- Fully automated CI/CD pipelines and GitOps integration.
- Real-time metrics and logging for actionable insights.
The
nlohmann/json
library, often referred to as "JSON for Modern C++," is a popular open-source, header-only library that simplifies working with JSON data in C++. It provides an intuitive syntax and integrates seamlessly with C++'s Standard Template Library (STL), making JSON parsing and serialization straightforward for developers.
Key Features
Getting Started
Installation
Since
nlohmann/json
is a header-only library, installation is straightforward:
Download the Header
: Obtain the
json.hpp
file from the
official GitHub repository
.
Include in Your Project
: Place
json.hpp
in your project's include path.
Include in Code : In your C++ source files, include the header:
#include <nlohmann/json.hpp> using json = nlohmann::json;
Basic Usage
Creating JSON Objects
You can create JSON objects using initializer lists:
json j = { {"name", "John Doe"}, {"age", 30}, {"is_student", false}, {"skills", {"C++", "Python", "JavaScript"}}Parsing JSON Strings
To parse a JSON string:
std::string json_str = R"({"name": "Jane Doe", "age": 25})"; json j = json::parse(json_str);Accessing and Modifying Values
Access elements using
[]or.at():std::string name = j["name"]; int age = j.at("age");Modify values similarly:
j ["age"] = 26;Serialization
Convert JSON objects to strings:
std::string serialized = j.dump(); // Compact representation std::string pretty = j.dump(4); // Pretty-printed with 4-space indentationAdvanced Features
Working with Files
Read from a file:
std::ifstream input_file("data.json"); json j; input_file >> j;Write to a file:
std::ofstream output_file("output.json"); output_file << j.dump(4);Custom Type Serialization
To serialize and deserialize custom C++ types, define
to_jsonandfrom_jsonfunctions:struct Person { std::string name; int age; void to_json(json& j, const Person& p) { j = json{{"name", p.name}, {"age", p.age}}; void from_json(const json& j, Person& p) { j.at("name").get_to(p.name); j.at("age").get_to(p.age);Now, you can serialize and deserialize
Personobjects:Person person = {"Alice", 28}; json j = person; Person new_person = j.get<Person>();Error Handling
Handle parsing errors using exceptions:
try { json j = json::parse(invalid_json_str); } catch (json::parse_error& e) { std::cerr << "Parse error: " << e.what() << std::endl;Conclusion
The
nlohmann/jsonlibrary offers a modern and intuitive approach to handling JSON in C++. Its seamless integration with C++ features and STL containers makes it a valuable tool for developers working with JSON data. Whether you're reading configuration files, interacting with web APIs, or storing structured data,nlohmann/jsonsimplifies the process and enhances code readability.FAQs
Yes, it requires C++11 or later due to its use of modern features.
Yes, you can use standard file streams to read JSON into a
jsonobject.Define
to_jsonandfrom_jsonfunctions for your type.We are Leapcell, your top choice for hosting backend projects.
Leapcell is the Next-Gen Serverless Platform for Web Hosting, Async Tasks, and Redis:
Multi-Language Support
Deploy unlimited projects for free
Unbeatable Cost Efficiency
Streamlined Developer Experience
Effortless Scalability and High Performance