Language: CPP
Web
nlohmann-json was created by Niels Lohmann in 2013 to offer a simple, intuitive, and type-safe way to handle JSON in C++. It quickly became popular due to its ease of use, compatibility with modern C++ standards, and rich feature set.
nlohmann-json is a modern C++ library for parsing, serializing, and manipulating JSON data. It provides an easy-to-use, STL-like interface and is header-only, making integration straightforward.
sudo apt install nlohmann-json3-devbrew install nlohmann-jsonDownload single header from https://github.com/nlohmann/json/releases or use vcpkg: vcpkg install nlohmann-jsonnlohmann-json allows creating JSON objects, parsing JSON strings, and serializing JSON data. It provides STL-like access, iterators, and convenient methods for manipulating nested data structures.
#include <nlohmann/json.hpp>
#include <iostream>
using json = nlohmann::json;
int main() {
json j;
j["name"] = "Alice";
j["age"] = 30;
std::cout << j["name"] << " is " << j["age"] << " years old." << std::endl;
return 0;
}Creates a JSON object and accesses its fields using string keys.
#include <nlohmann/json.hpp>
#include <iostream>
#include <string>
using json = nlohmann::json;
int main() {
std::string s = R"({"city":"NYC","population":8419000})";
json j = json::parse(s);
std::cout << j["city"] << std::endl;
return 0;
}Parses a JSON-formatted string into a JSON object and accesses its values.
#include <nlohmann/json.hpp>
#include <iostream>
using json = nlohmann::json;
int main() {
json j = { {"name", "Alice"}, {"age", 30} };
for (auto& [key, value] : j.items()) {
std::cout << key << ": " << value << std::endl;
}
return 0;
}Demonstrates iterating over JSON key-value pairs using structured bindings.
#include <nlohmann/json.hpp>
#include <iostream>
using json = nlohmann::json;
int main() {
json j = { {"name", "Bob"}, {"active", true} };
std::string s = j.dump(4); // pretty print with 4 spaces
std::cout << s << std::endl;
return 0;
}Serializes a JSON object into a formatted string for readability.
#include <nlohmann/json.hpp>
#include <iostream>
using json = nlohmann::json;
int main() {
json j = {"apple", "banana", "cherry"};
j.push_back("date");
for (auto& fruit : j) std::cout << fruit << std::endl;
return 0;
}Demonstrates creating a JSON array, adding elements, and iterating through it.
Prefer `json::parse` with try-catch blocks to handle malformed input.
Use `dump()` with indentation for human-readable JSON output.
Leverage STL-like iterators for manipulation of objects and arrays.
Validate JSON structure before accessing deeply nested fields.
Keep library updated to benefit from new C++ standard support and bug fixes.