json – nlohmann
现代 C++ 的 JSON
关键指标一览
主题标签
README 详细介绍
<img src="https://ci.appveyor.com/api/projects/status/1acb366xfyg3qybk/branch/develop?svg=true" alt="Build Status" class="ra0-md-img" loading="lazy" />
<img src="https://github.com/nlohmann/json/workflows/Ubuntu/badge.svg" alt="Ubuntu" class="ra0-md-img" loading="lazy" />
<img src="https://github.com/nlohmann/json/workflows/macOS/badge.svg" alt="macOS" class="ra0-md-img" loading="lazy" />
<img src="https://github.com/nlohmann/json/workflows/Windows/badge.svg" alt="Windows" class="ra0-md-img" loading="lazy" />
<img src="https://coveralls.io/repos/github/nlohmann/json/badge.svg?branch=develop" alt="Coverage Status" class="ra0-md-img" loading="lazy" />
<img src="https://scan.coverity.com/projects/5550/badge.svg" alt="Coverity Scan Build Status" class="ra0-md-img" loading="lazy" />
<img src="https://app.codacy.com/project/badge/Grade/e0d1a9d5d6fd46fcb655c4cb930bb3e8" alt="Codacy Badge" class="ra0-md-img" loading="lazy" />
<img src="https://api.cirrus-ci.com/github/nlohmann/json.svg" alt="Cirrus CI" class="ra0-md-img" loading="lazy" />
<img src="https://oss-fuzz-build-logs.storage.googleapis.com/badges/json.svg" alt="Fuzzing Status" class="ra0-md-img" loading="lazy" />
<img src="https://img.shields.io/badge/try-online-blue.svg" alt="Try online" class="ra0-md-img" loading="lazy" />
<img src="https://img.shields.io/badge/docs-mkdocs-blue.svg" alt="Documentation" class="ra0-md-img" loading="lazy" />
<img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="GitHub license" class="ra0-md-img" loading="lazy" />
<img src="https://img.shields.io/github/release/nlohmann/json.svg" alt="GitHub Releases" class="ra0-md-img" loading="lazy" />
<img src="https://repology.org/badge/tiny-repos/nlohmann-json.svg" alt="Packaging status" class="ra0-md-img" loading="lazy" />
<img src="https://img.shields.io/github/downloads/nlohmann/json/total" alt="GitHub Downloads" class="ra0-md-img" loading="lazy" />
<img src="https://img.shields.io/github/issues/nlohmann/json.svg" alt="GitHub Issues" class="ra0-md-img" loading="lazy" />
[](https://isitmaintained.com/project/nlohmann/json "Average time to resolve an issue")
<img src="https://bestpractices.coreinfrastructure.org/projects/289/badge" alt="CII Best Practices" class="ra0-md-img" loading="lazy" />
<img src="https://api.scorecard.dev/projects/github.com/nlohmann/json/badge" alt="OpenSSF Scorecard" class="ra0-md-img" loading="lazy" />
<img src="https://app.cloudback.it/badge/nlohmann/json" alt="Backup Status" class="ra0-md-img" loading="lazy" />
<img src="https://img.shields.io/badge/GitHub-Sponsors-ff69b4" alt="GitHub Sponsors" class="ra0-md-img" loading="lazy" />
<img src="https://api.reuse.software/badge/github.com/nlohmann/json" alt="REUSE status" class="ra0-md-img" loading="lazy" />
<img src="https://img.shields.io/discord/1003743314341793913" alt="Discord" class="ra0-md-img" loading="lazy" />
- Design goals
- Sponsors
- Support (documentation, FAQ, discussions, API, bug issues)
- Quick reference
- Examples
- Read JSON from a file
- Creating <code class="ra0-md-code">json</code> objects from JSON literals
- JSON as a first-class data type
- Serialization / Deserialization
- STL-like access
- Conversion from STL containers
- JSON Pointer and JSON Patch
- JSON Merge Patch
- Implicit conversions
- Conversions to/from arbitrary types
- Specializing enum conversion
- Binary formats (BSON, CBOR, MessagePack, UBJSON, and BJData)
- Customers
- Ecosystem
- Supported compilers
- Integration
- CMake
- Package Managers
- Pkg-config
- License
- Contact
- Thanks
- Used third-party tools
- Notes
- Execute unit tests
Design goals
There are myriads of JSON libraries out there, and each may even have its reason to exist. Our class had these design goals:
- Intuitive syntax*. In languages such as Python, JSON feels like a first-class data type. We used all the operator magic of modern C++ to achieve the same feeling in your code. Check out the examples below and you'll know what I mean.
- Trivial integration*. Our whole code consists of a single header file <code class="ra0-md-code">json.hpp</code>. That's it. No library, no subproject, no dependencies, no complex build system. The class is written in vanilla C++11. All in all, everything should require no adjustment of your compiler flags or project settings. The library is also included in all popular package managers.
- Serious testing*. Our code is heavily unit-tested and covers 100% of the code, including all exceptional behavior. Furthermore, we checked with Valgrind and the Clang Sanitizers that there are no memory leaks. Google OSS-Fuzz additionally runs fuzz tests against all parsers 24/7, effectively executing billions of tests so far. To maintain high quality, the project is following the Core Infrastructure Initiative (CII) best practices. See the quality assurance overview documentation.
Other aspects were not so important to us:
- Memory efficiency*. Each JSON object has an overhead of one pointer (the maximal size of a union) and one enumeration element (1 byte). The default generalization uses the following C++ data types:
std::stringfor strings,int64_t,uint64_tordoublefor numbers,std::mapfor objects,std::vectorfor arrays, andboolfor Booleans. However, you can template the generalized classbasic_jsonto your needs.
- Speed*. There are certainly faster JSON libraries out there. However, if your goal is to speed up your development by adding JSON support with a single header, then this library is the way to go. If you know how to use a
std::vectororstd::map, you are already set.
See the contribution guidelines for more information.
Sponsors
You can sponsor this library at GitHub Sponsors.
:raising_hand: Priority Sponsor
:label: Named Sponsors
Further support
The development of the library is further supported by JetBrains by providing free access to their IDE tools.
Thanks everyone!
Support
:question: If you have a question, please check if it is already answered in the FAQ or the Q&A section. If not, please ask a new question there.
:books: If you want to learn more about how to use the library, check out the rest of the README, have a look at code examples, or browse through the help pages.
:construction: If you want to understand the API better, check out the API Reference or have a look at the quick reference below.
:bug: If you found a bug, please check the FAQ if it is a known issue or the result of a design decision. Please also have a look at the issue list before you create a new issue. Please provide as much information as possible to help us understand and reproduce your issue.
There is also a docset* for the documentation browsers Dash, Velocity, and Zeal that contains the full documentation as an offline resource.
Quick reference
- Constructors* basic_json, array, binary, object
- Object inspection*: type, operator value_t, type_name, is_primitive, is_structured, is_null, is_boolean, is_number, is_number_integer, is_number_unsigned, is_number_float, is_object, is_array, is_string, is_binary, is_discarded
- Value access*; get, get_to, get_ptr, get_ref, operator ValueType, get_binary
- Element access*: at, [operator[]](https://json.nlohmann.me/api/basic_json/operator[]), value, front, back
- Lookup*: find, count, contains
- Iterators*: begin, cbegin, end, cend, rbegin, rend, crbegin, crend, items
- Capacity*: empty, size, max_size
- Modifiers*: clear, push_back, operator+=, emplace_back, emplace, erase, insert, update, swap
- Lexicographical comparison operators*: operator==, operator!=, operator<, operator>, operator<=, operator>=, operator<=>
- Serialization / Dumping*: dump
- Deserialization / Parsing*: parse, accept, sax_parse
- JSON Pointer functions*: flatten, unflatten
- JSON Patch functions*: patch, patch_inplace, diff, merge_patch
- Static functions*: meta, get_allocator
- Binary formats*: from_bjdata, from_bson, from_cbor, from_msgpack, from_ubjson, to_bjdata, to_bson, to_cbor, to_msgpack, to_ubjson
- Non-member functions*: operator<<, operator>>, to_string
- Literals*: operator""_json
- Helper classes*: std::hash<basic_json>, std::swap<basic_json>
Examples
Here are some examples to give you an idea how to use the class.
Besides the examples below, you may want to:
→ Check the documentation
→ Browse the standalone example files
→ Read the full API Documentation with self-contained examples for every function
Read JSON from a file
The json class provides an API for manipulating a JSON value. To create a json object by reading a JSON file:
#include <fstream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
// ...
std::ifstream f("example.json");
json data = json::parse(f);
If using modules (enabled with NLOHMANN_JSON_BUILD_MODULES), this example becomes:
import std;
import nlohmann.json;
using json = nlohmann::json;
// ...
std::ifstream f("example.json");
json data = json::parse(f);
Creating json objects from JSON literals
Assume you want to hard-code this literal JSON value as a json object:
{
"pi": 3.141,
"happy": true
}
There are various options:
// Using (raw) string literals and json::parse
json ex1 = json::parse(R"(
{
"pi": 3.141,
"happy": true
}
)");
// Using user-defined (raw) string literals
using namespace nlohmann::literals;
json ex2 = R"(
{
"pi": 3.141,
"happy": true
}
)"_json;
// Using initializer lists
json ex3 = {
{"happy", true},
{"pi", 3.141},
};
JSON as a first-class data type
Here are some examples to give you an idea how to use the class.
Assume you want to create the JSON object
{
"pi": 3.141,
"happy": true,
"name": "Niels",
"nothing": null,
"answer": {
"everything": 42
},
"list": [1, 0, 2],
"object": {
"currency": "USD",
"value": 42.99
}
}
With this library, you could write:
// create an empty structure (null)
json j;
// add a number stored as double (note the implicit conversion of j to an object)
j["pi"] = 3.141;
// add a Boolean stored as bool
j["happy"] = true;
// add a string stored as std::string
j["name"] = "Niels";
// add another null object by passing nullptr
j["nothing"] = nullptr;
// add an object inside the object
j["answer"]["everything"] = 42;
// add an array stored as std::vector (using an initializer list)
j["list"] = { 1, 0, 2 };
// add another object (using an initializer list of pairs)
j["object"] = { {"currency", "USD"}, {"value", 42.99} };
// instead, you could also write (which looks very similar to the JSON above)
json j2 = {
{"pi", 3.141},
{"happy", true},
{"name", "Niels"},
{"nothing", nullptr},
{"answer", {
{"everything", 42}
}},
{"list", {1, 0, 2}},
{"object", {
{"currency", "USD"},
{"value", 42.99}
}}
};
Note that in all these cases, you never need to "tell" the compiler which JSON value type you want to use. If you want to be explicit or express some edge cases, the functions <code class="ra0-md-code">json::array()</code> and <code class="ra0-md-code">json::object()</code> will help:
// a way to express the empty array []
json empty_array_explicit = json::array();
// ways to express the empty object {}
json empty_object_implicit = json({});
json empty_object_explicit = json::object();
// a way to express an _array_ of key/value pairs [["currency", "USD"], ["value", 42.99]]
json array_not_object = json::array({ {"currency", "USD"}, {"value", 42.99} });
Serialization / Deserialization
To/from strings
You can create a JSON value (deserialization) by appending _json to a string literal:
// create object from string literal
json j = "{ "happy": true, "pi": 3.141 }"_json;
// or even nicer with a raw string literal
auto j2 = R"(
{
"happy": true,
"pi": 3.141
}
)"_json;
Note that without appending the _json suffix, the passed string literal is not parsed, but just used as JSON string
value. That is, json j = "{ "happy": true, "pi": 3.141 }" would just store the string"{ "happy": true, "pi": 3.141 }" rather than parsing the actual object.
The string literal should be brought into scope with using namespace nlohmann::literals;
(see <code class="ra0-md-code">json::parse()</code>).
The above example can also be expressed explicitly using <code class="ra0-md-code">json::parse()</code>:
// parse explicitly
auto j3 = json::parse(R"({"happy": true, "pi": 3.141})");
You can also get a string representation of a JSON value (serialize):
// explicit conversion to string
std::string s = j.dump(); // {"happy":true,"pi":3.141}
// serialization with pretty printing
// pass in the amount of spaces to indent
std::cout << j.dump(4) << std::endl;
// {
// "happy": true,
// "pi": 3.141
// }
Note the difference between serialization and assignment:
// store a string in a JSON value
json j_string = "this is a string";
// retrieve the string value
auto cpp_string = j_string.get<std::string>();
// retrieve the string value (alternative when a variable already exists)
std::string cpp_string2;
j_string.get_to(cpp_string2);
// retrieve the serialized value (explicit JSON serialization)
std::string serialized_string = j_string.dump();
// output of original string
std::cout << cpp_string << " == " << cpp_string2 << " == " << j_string.get<std::string>() << 'n';
// output of serialized value
std::cout << j_string << " == " << serialized_string << std::endl;
<code class="ra0-md-code">.dump()</code> returns the originally stored string value.
Note the library only supports UTF-8. When you store strings with different encodings in the library, calling <code class="ra0-md-code">dump()</code> may throw an exception unless json::error_handler_t::replace or json::error_handler_t::ignore are used as error handlers.
To/from streams (e.g., files, string streams)
You can also use streams to serialize and deserialize:
// deserialize from standard input
json j;
std::cin >> j;
// serialize to standard output
std::cout << j;
// the setw manipulator was overloaded to set the indentation for pretty printing
std::cout << std::setw(4) << j << std::endl;
These operators work for any subclasses of std::istream or std::ostream. Here is the same example with files:
// read a JSON file
std::ifstream i("file.json");
json j;
i >> j;
// write prettified JSON to another file
std::ofstream o("pretty.json");
o << std::setw(4) << j << std::endl;
Please note that setting the exception bit for failbit is inappropriate for this use case. It will result in program termination due to the noexcept specifier in use.
Read from iterator range
You can also parse JSON from an iterator range; that is, from any container accessible by iterators whose value_type is an integral type of 1, 2, or 4 bytes, which will be interpreted as UTF-8, UTF-16, and UTF-32 respectively. For instance, a std::vector<std::uint8_t>, or a std::list<std::uint16_t>:
std::vector<std::uint8_t> v = {'t', 'r', 'u', 'e'};
json j = json::parse(v.begin(), v.end());
You may leave the iterators for the range [begin, end):
std::vector<std::uint8_t> v = {'t', 'r', 'u', 'e'};
json j = json::parse(v);
Custom data source
Since the parse function accepts arbitrary iterator ranges, you can provide your own data sources by implementing the LegacyInputIterator concept.
struct MyContainer {
void advance();
const char& get_current();
};
struct MyIterator {
using difference_type = std::ptrdiff_t;
using value_type = char;
using pointer = const char*;
using reference = const char&;
using iterator_category = std::input_iterator_tag;
explicit MyIterator(MyContainer* tgt = nullptr) : target(tgt) {}
MyIterator& operator++() {
target->advance();
return *this;
}
bool operator!=(const MyIterator& rhs) const {
return rhs.target != target;
}
reference operator*() const {
return target->get_current();
}
MyContainer* target = nullptr;
};
MyIterator begin(MyContainer& tgt) {
return MyIterator{&tgt};
}
MyIterator end(const MyContainer&) {
return MyIterator{};
}
void foo() {
MyContainer c;
json j = json::parse(begin(c), end(c));
}
SAX interface
The library uses a SAX-like interface with the following functions:
// called when null is parsed
bool null();
// called when a boolean is parsed; value is passed
bool boolean(bool val);
// called when a signed or unsigned integer number is parsed; value is passed
bool number_integer(number_integer_t val);
bool number_unsigned(number_unsigned_t val);
// called when a floating-point number is parsed; value and original string is passed
bool number_float(number_float_t val, const string_t& s);
// called when a string is parsed; value is passed and can be safely moved away
bool string(string_t& val);
// called when a binary value is parsed; value is passed and can be safely moved away
bool binary(binary_t& val);
// called when an object or array begins or ends, resp. The number of elements is passed (or -1 if not known)
bool start_object(std::size_t elements);
bool end_object();
bool start_array(std::size_t elements);
bool end_array();
// called when an object key is parsed; value is passed and can be safely moved away
bool key(string_t& val);
// called when a parse error occurs; byte position, the last token, and an exception is passed
bool parse_error(std::size_t position, const std::string& last_token, const detail::exception& ex);
The return value of each function determines whether parsing should proceed.
To implement your own SAX handler, proceed as follows:
- Implement the SAX interface in a class. You can use class
nlohmann::json_sax<json>as base class, but you can also use any class where the functions described above are implemented and public. - Create an object of your SAX interface class, e.g.
my_sax. - Call
bool json::sax_parse(input, &my_sax); where the first parameter can be any input like a string or an input stream and the second parameter is a pointer to your SAX interface.
Note the sax_parse function only returns a bool indicating the result of the last executed SAX event. It does not return a json value - it is up to you to decide what to do with the SAX events. Furthermore, no exceptions are thrown in case of a parse error -- it is up to you what to do with the exception object passed to your parse_error implementation. Internally, the SAX interface is used for the DOM parser (class json_sax_dom_parser) as well as the acceptor (json_sax_acceptor), see file <code class="ra0-md-code">json_sax.hpp</code>.
STL-like access
We designed the JSON class to behave just like an STL container. In fact, it satisfies the ReversibleContainer* requirement.
// create an array using push_back
json j;
j.push_back("foo");
j.push_back(1);
j.push_back(true);
// also use emplace_back
j.emplace_back(1.78);
// iterate the array
for (json::iterator it = j.begin(); it != j.end(); ++it) {
std::cout << *it << 'n';
}
// range-based for
for (auto& element : j) {
std::cout << element << 'n';
}
// getter/setter
const auto tmp = j[0].get<std::string>();
j[1] = 42;
bool foo = j.at(2);
// comparison
j == R"(["foo", 1, true, 1.78])"_json; // true
// other stuff
j.size(); // 4 entries
j.empty(); // false
j.type(); // json::value_t::array
j.clear(); // the array is empty again
// convenience type checkers
j.is_null();
j.is_boolean();
j.is_number();
j.is_object();
j.is_array();
j.is_string();
// create an object
json o;
o["foo"] = 23;
o["bar"] = false;
o["baz"] = 3.141;
// also use emplace
o.emplace("weather", "sunny");
// special iterator member functions for objects
for (json::iterator it = o.begin(); it != o.end(); ++it) {
std::cout << it.key() << " : " << it.value() << "n";
}
// the same code as range for
for (auto& el : o.items()) {
std::cout << el.key() << " : " << el.value() << "n";
}
// even easier with structured bindings (C++17)
for (auto& [key, value] : o.items()) {
std::cout << key << " : " << value << "n";
}
// find an entry
if (o.contains("foo")) {
// there is an entry with key "foo"
}
// or via find and an iterator
if (o.find("foo") != o.end()) {
// there is an entry with key "foo"
}
// or simpler using count()
int foo_present = o.count("foo"); // 1
int fob_present = o.count("fob"); // 0
// delete an entry
o.erase("foo");
Conversion from STL containers
Any sequence container (std::array, std::vector, std::deque, std::forward_list, std::list) whose values can be used to construct JSON values (e.g., integers, floating point numbers, Booleans, string types, or again STL containers described in this section) can be used to create a JSON array. The same holds for similar associative containers (std::set, std::multiset, std::unordered_set, std::unordered_multiset), but in these cases the order of the elements of the array depends on how the elements are ordered in the respective STL container.
std::vector<int> c_vector {1, 2, 3, 4};
json j_vec(c_vector);
// [1, 2, 3, 4]
std::deque<double> c_deque {1.2, 2.3, 3.4, 5.6};
json j_deque(c_deque);
// [1.2, 2.3, 3.4, 5.6]
std::list<bool> c_list {true, true, false, true};
json j_list(c_list);
// [true, true, false, true]
std::forward_list<int64_t> c_flist {12345678909876, 23456789098765, 34567890987654, 45678909876543};
json j_flist(c_flist);
// [12345678909876, 23456789098765, 34567890987654, 45678909876543]
std::array<unsigned long, 4> c_array {{1, 2, 3, 4}};
json j_array(c_array);
// [1, 2, 3, 4]
std::set<std::string> c_set {"one", "two", "three", "four", "one"};
json j_set(c_set); // only one entry for "one" is used
// ["four", "one", "three", "two"]
std::unordered_set<std::string> c_uset {"one", "two", "three", "four", "one"};
json j_uset(c_uset); // only one entry for "one" is used
// maybe ["two", "three", "four", "one"]
std::multiset<std::string> c_mset {"one", "two", "one", "four"};
json j_mset(c_mset); // both entries for "one" are used
// maybe ["one", "two", "one", "four"]
std::unordered_multiset<std::string> c_umset {"one", "two", "one", "four"};
json j_umset(c_umset); // both entries for "one" are used
// maybe ["one", "two", "one", "four"]
Likewise, any associative key-value containers (std::map, std::multimap, std::unordered_map, std::unordered_multimap) whose keys can construct an std::string and whose values can be used to construct JSON values (see examples above) can be used to create a JSON object. Note that in case of multimaps, only one key is used in the JSON object and the value depends on the internal order of the STL container.
std::map<std::string, int> c_map { {"one", 1}, {"two", 2}, {"three", 3} };
json j_map(c_map);
// {"one": 1, "three": 3, "two": 2 }
std::unordered_map<const char*, double> c_umap { {"one", 1.2}, {"two", 2.3}, {"three", 3.4} };
json j_umap(c_umap);
// {"one": 1.2, "two": 2.3, "three": 3.4}
std::multimap<std::string, bool> c_mmap { {"one", true}, {"two", true}, {"three", false}, {"three", true} };
json j_mmap(c_mmap); // only one entry for key "three" is used
// maybe {"one": true, "two": true, "three": true}
std::unordered_multimap<std::string, bool> c_ummap { {"one", true}, {"two", true}, {"three", false}, {"three", true} };
json j_ummap(c_ummap); // only one entry for key "three" is used
// maybe {"one": true, "two": true, "three": true}
JSON Pointer and JSON Patch
The library supports JSON Pointer (RFC 6901) as an alternative means to address structured values. On top of this, JSON Patch (RFC 6902) allows describing differences between two JSON values -- effectively allowing patch and diff operations known from Unix.
// a JSON value
json j_original = R"({
"baz": ["one", "two", "three"],
"foo": "bar"
})"_json;
// access members with a JSON pointer (RFC 6901)
j_original["/baz/1"_json_pointer];
// "two"
// a JSON patch (RFC 6902)
json j_patch = R"([
{ "op": "replace", "path": "/baz", "value": "boo" },
{ "op": "add", "path": "/hello", "value": ["world"] },
{ "op": "remove", "path": "/foo"}
])"_json;
// apply the patch
json j_result = j_original.patch(j_patch);
// {
// "baz": "boo",
// "hello": ["world"]
// }
// calculate a JSON patch from two JSON values
json::diff(j_result, j_original);
// [
// { "op":" replace", "path": "/baz", "value": ["one", "two", "three"] },
// { "op": "remove","path": "/hello" },
// { "op": "add", "path": "/foo", "value": "bar" }
// ]
JSON Merge Patch
The library supports JSON Merge Patch* (RFC 7386) as a patch format. Instead of using JSON Pointer (see above) to specify values to be manipulated, it describes the changes using a syntax that closely mimics the document being modified.
// a JSON value
json j_document = R"({
"a": "b",
"c": {
"d": "e",
"f": "g"
}
})"_json;
// a patch
json j_patch = R"({
"a":"z",
"c": {
"f": null
}
})"_json;
// apply the patch
j_document.merge_patch(j_patch);
// {
// "a": "z",
// "c": {
// "d": "e"
// }
// }
Implicit conversions
Supported types can be implicitly converted to JSON values.
It is recommended to NOT USE implicit conversions FROM a JSON value.
You can find more details about this recommendation here.
You can switch off implicit conversions by defining JSON_USE_IMPLICIT_CONVERSIONS to 0 before including the json.hpp header. When using CMake, you can also achieve this by setting the option JSON_ImplicitConversions to OFF.
// strings
std::string s1 = "Hello, world!";
json js = s1;
auto s2 = js.get<std::string>();
// NOT RECOMMENDED
std::string s3 = js;
std::string s4;
s4 = js;
// Booleans
bool b1 = true;
json jb = b1;
auto b2 = jb.get<bool>();
// NOT RECOMMENDED
bool b3 = jb;
bool b4;
b4 = jb;
// numbers
int i = 42;
json jn = i;
auto f = jn.get<double>();
// NOT RECOMMENDED
double f2 = jn;
double f3;
f3 = jn;
// etc.
Note that char types are not automatically converted to JSON strings, but to integer numbers. A conversion to a string must be specified explicitly:
char ch = 'A'; // ASCII value 65
json j_default = ch; // stores integer number 65
json j_string = std::string(1, ch); // stores string "A"
Arbitrary types conversions
Every type can be serialized in JSON, not just STL containers and scalar types. Usually, you would do something along those lines:
namespace ns {
// a simple struct to model a person
struct person {
std::string name;
std::string address;
int age;
};
}
ns::person p = {"Ned Flanders", "744 Evergreen Terrace", 60};
// convert to JSON: copy each value into the JSON object
json j;
j["name"] = p.name;
j["address"] = p.address;
j["age"] = p.age;
// ...
// convert from JSON: copy each value from the JSON object
ns::person p {
j["name"].get<std::string>(),
j["address"].get<std::string>(),
j["age"].get<int>()
};
It works, but that's quite a lot of boilerplate... Fortunately, there's a better way:
// create a person
ns::person p {"Ned Flanders", "744 Evergreen Terrace", 60};
// conversion: person -> json
json j = p;
std::cout << j << std::endl;
// {"address":"744 Evergreen Terrace","age":60,"name":"Ned Flanders"}
// conversion: json -> person
auto p2 = j.get<ns::person>();
// that's it
assert(p == p2);
Basic usage
To make this work with one of your types, you only need to provide two functions:
using json = nlohmann::json;
namespace ns {
void to_json(json& j, const person& p) {
j = json{{"name", p.name}, {"address", p.address}, {"age", p.age}};
}
void from_json(const json& j, person& p) {
j.at("name").get_to(p.name);
j.at("address").get_to(p.address);
j.at("age").get_to(p.age);
}
} // namespace ns
That's all! When calling the json constructor with your type, your custom to_json method will be automatically called.
Likewise, when calling get<your_type>() or get_to(your_type&), the from_json method will be called.
Some important things:
- Those methods MUST* be in your type's namespace (which can be the global namespace), or the library will not be able to locate them (in this example, they are in namespace
ns, wherepersonis defined). - Those methods MUST* be available (e.g., proper headers must be included) everywhere you use these conversions. Look at issue 1108 for errors that may occur otherwise.
- When using
get<your_type>(),your_typeMUST* be DefaultConstructible. (There is a way to bypass this requirement described later.) - In function
from_json, use function <code class="ra0-md-code">at()</code> to access the object values rather thanoperator[]. In case a key does not exist,atthrows an exception that you can handle, whereasoperator[]exhibits undefined behavior. - You do not need to add serializers or deserializers for STL types like
std::vector: the library already implements these.
Simplify your life with macros
If you just want to serialize/deserialize some structs, the to_json/from_json functions can be a lot of boilerplate. There are several macros* to make your life easier as long as you want to use a JSON object as serialization.
Which macro to choose depends on whether private member variables need to be accessed, a deserialization is needed, missing values should yield an error or should be replaced by default values, and if derived classes are used. See this overview to choose the right one for your use case.
Example usage of macros
The to_json/from_json functions for the person struct above can be created with <code class="ra0-md-code">NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE</code>. In all macros, the first parameter is the name of the class/struct, and all remaining parameters name the members.
namespace ns {
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(person, name, address, age)
}
If you want to inherit the person struct and add a field to it, it can be done with:
namespace ns {
struct person_derived : person {
std::string email;
};
NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE(person_derived, person, email)
}
Here is another example with private members, where <code class="ra0-md-code">NLOHMANN_DEFINE_TYPE_INTRUSIVE</code> is needed:
namespace ns {
class address {
private:
std::string street;
int housenumber;
int postcode;
public:
NLOHMANN_DEFINE_TYPE_INTRUSIVE(address, street, housenumber, postcode)
};
}
Or in case if you use some naming convention that you do not want to expose to JSON:
namespace ns {
class address {
private:
std::string m_street;
int m_housenumber;
int m_postcode;
public:
NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_NAMES(address, "street", m_street,
"housenumber", m_housenumber,
"postcode", m_postcode)
};
}
How do I convert third-party types?
This requires a bit more advanced technique. But first, let's see how this conversion mechanism works:
The library uses JSON Serializers* to convert types to JSON.
The default serializer for nlohmann::json is nlohmann::adl_serializer (ADL means Argument-Dependent Lookup).
It is implemented like this (simplified):
template <typename T>
struct adl_serializer {
static void to_json(json& j, const T& value) {
// calls the "to_json" method in T's namespace
}
static void from_json(const json& j, T& value) {
// same thing, but with the "from_json" method
}
};
This serializer works fine when you have control over the type's namespace. However, what about boost::optional or std::filesystem::path (C++17)? Hijacking the boost namespace is pretty bad, and it's illegal to add something other than template specializations to std...
To solve this, you need to add a specialization of adl_serializer to the nlohmann namespace, here's an example:
// partial specialization (full specialization works too)
namespace nlohmann {
template <typename T>
struct adl_serializer<boost::optional<T>> {
static void to_json(json& j, const boost::optional<T>& opt) {
if (opt == boost::none) {
j = nullptr;
} else {
j = *opt; // this will call adl_serializer<T>::to_json which will
// find the free function to_json in T's namespace!
}
}
static void from_json(const json& j, boost::optional<T>& opt) {
if (j.is_null()) {
opt = boost::none;
} else {
opt = j.get<T>(); // same as above, but with
// adl_serializer<T>::from_json
}
}
};
}
How can I use get() for non-default constructible/non-copyable types?
There is a way if your type is MoveConstructible. You will need to specialize the adl_serializer as well, but with a special from_json overload:
struct move_only_type {
move_only_type() = delete;
move_only_type(int ii): i(ii) {}
move_only_type(const move_only_type&) = delete;
move_only_type(move_only_type&&) = default;
int i;
};
namespace nlohmann {
template <>
struct adl_serializer<move_only_type> {
// note: the return type is no longer 'void', and the method only takes
// one argument
static move_only_type from_json(const json& j) {
return {j.get<int>()};
}
// Here's the catch! You must provide a to_json method! Otherwise, you
// will not be able to convert move_only_type to json, since you fully
// specialized adl_serializer on that type
static void to_json(json& j, move_only_type t) {
j = t.i;
}
};
}
Can I write my own serializer? (Advanced use)
Yes. You might want to take a look at <code class="ra0-md-code">unit-udt.cpp</code> in the test suite, to see a few examples.
If you write your own serializer, you'll need to do a few things:
- use a different
basic_jsonalias thannlohmann::json(the last template parameter ofbasic_jsonis theJSONSerializer) - use your
basic_jsonalias (or a template parameter) in all yourto_json/from_jsonmethods - use
nlohmann::to_jsonandnlohmann::from_jsonwhen you need ADL
Here is an example, without simplifications, that only accepts types with a size <= 32, and uses ADL.
// You should use void as a second template argument
// if you don't need compile-time checks on T
template<typename T, typename SFINAE = typename std::enable_if<sizeof(T) <= 32>::type>
struct less_than_32_serializer {
template <typename BasicJsonType>
static void to_json(BasicJsonType& j, T value) {
// we want to use ADL, and call the correct to_json overload
using nlohmann::to_json; // this method is called by adl_serializer,
// this is where the magic happens
to_json(j, value);
}
template <typename BasicJsonType>
static void from_json(const BasicJsonType& j, T& value) {
// same thing here
using nlohmann::from_json;
from_json(j, value);
}
};
Be very* careful when reimplementing your serializer, you can stack overflow if you don't pay attention:
template <typename T, void>
struct bad_serializer
{
template <typename BasicJsonType>
static void to_json(BasicJsonType& j, const T& value) {
// this calls BasicJsonType::json_serializer<T>::to_json(j, value)
// if BasicJsonType::json_serializer == bad_serializer ... oops!
j = value;
}
template <typename BasicJsonType>
static void to_json(const BasicJsonType& j, T& value) {
// this calls BasicJsonType::json_serializer<T>::from_json(j, value)
// if BasicJsonType::json_serializer == bad_serializer ... oops!
value = j.get<T>(); // oops!
}
};
Specializing enum conversion
By default, enum values are serialized to JSON as integers. In some cases, this could result in undesired behavior. If an enum is modified or re-ordered after data has been serialized to JSON, the later deserialized JSON data may be undefined or a different enum value than was originally intended.
It is possible to more precisely specify how a given enum is mapped to and from JSON as shown below:
// example enum type declaration
enum TaskState {
TS_STOPPED,
TS_RUNNING,
TS_COMPLETED,
TS_INVALID=-1,
};
// map TaskState values to JSON as strings
NLOHMANN_JSON_SERIALIZE_ENUM( TaskState, {
{TS_INVALID, nullptr},
{TS_STOPPED, "stopped"},
{TS_RUNNING, "running"},
{TS_COMPLETED, "completed"},
})
The NLOHMANN_JSON_SERIALIZE_ENUM() macro declares a set of to_json() / from_json() functions for type TaskState while avoiding repetition and boilerplate serialization code.
Usage:*
// enum to JSON as string
json j = TS_STOPPED;
assert(j == "stopped");
// json string to enum
json j3 = "running";
assert(j3.get<TaskState>() == TS_RUNNING);
// undefined json value to enum (where the first map entry above is the default)
json jPi = 3.14;
assert(jPi.get<TaskState>() == TS_INVALID);
Just as in Arbitrary Type Conversions above,
NLOHMANN_JSON_SERIALIZE_ENUM()MUST be declared in your enum type's namespace (which can be the global namespace), or the library will not be able to locate it, and it will default to integer serialization.- It MUST be available (e.g., proper headers must be included) everywhere you use the conversions.
Other Important points:
- When using
get<ENUM_TYPE>(), undefined JSON values will default to the first pair specified in your map. Select this default pair carefully. If you desire an exception in this circumstance useNLOHMANN_JSON_SERIALIZE_ENUM_STRICT()which behaves identically except for throwing an exception on unrecognized values. - If an enum or JSON value is specified more than once in your map, the first matching occurrence from the top of the map will be returned when converting to or from JSON.
Binary formats (BSON, CBOR, MessagePack, UBJSON, and BJData)
Though JSON is a ubiquitous data format, it is not a very compact format suitable for data exchange, for instance over a network. Hence, the library supports BSON (Binary JSON), CBOR (Concise Binary Object Representation), MessagePack, UBJSON (Universal Binary JSON Specification) and BJData (Binary JData) to efficiently encode JSON values to byte vectors and to decode such vectors.
// create a JSON value
json j = R"({"compact": true, "schema": 0})"_json;
// serialize to BSON
std::vector<std::uint8_t> v_bson = json::to_bson(j);
// 0x1B, 0x00, 0x00, 0x00, 0x08, 0x63, 0x6F, 0x6D, 0x70, 0x61, 0x63, 0x74, 0x00, 0x01, 0x10, 0x73, 0x63, 0x68, 0x65, 0x6D, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
// roundtrip
json j_from_bson = json::from_bson(v_bson);
// serialize to CBOR
std::vector<std::uint8_t> v_cbor = json::to_cbor(j);
// 0xA2, 0x67, 0x63, 0x6F, 0x6D, 0x70, 0x61, 0x63, 0x74, 0xF5, 0x66, 0x73, 0x63, 0x68, 0x65, 0x6D, 0x61, 0x00
// roundtrip
json j_from_cbor = json::from_cbor(v_cbor);
// serialize to MessagePack
std::vector<std::uint8_t> v_msgpack = json::to_msgpack(j);
// 0x82, 0xA7, 0x63, 0x6F, 0x6D, 0x70, 0x61, 0x63, 0x74, 0xC3, 0xA6, 0x73, 0x63, 0x68, 0x65, 0x6D, 0x61, 0x00
// roundtrip
json j_from_msgpack = json::from_msgpack(v_msgpack);
// serialize to UBJSON
std::vector<std::uint8_t> v_ubjson = json::to_ubjson(j);
// 0x7B, 0x69, 0x07, 0x63, 0x6F, 0x6D, 0x70, 0x61, 0x63, 0x74, 0x54, 0x69, 0x06, 0x73, 0x63, 0x68, 0x65, 0x6D, 0x61, 0x69, 0x00, 0x7D
// roundtrip
json j_from_ubjson = json::from_ubjson(v_ubjson);
The library also supports binary types from BSON, CBOR (byte strings), and MessagePack (bin, ext, fixext). They are stored by default as std::vector<std::uint8_t> to be processed outside the library.
```cpp
// CBOR byte string with payload 0xCAFE
std::vector<std::uint8_t> v = {0x42, 0xCA, 0xFE};
// read value
json j = json::from_cbor(v);
// the JSON value has type binary
j.is_binary(); // true
// get reference to stored binary value
auto& binary = j.get_binary();
<!-- README 已截断 -->