• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..16-Nov-2021-

LICENSE.MITH A D16-Nov-20211.1 KiB2217

README.mdH A D16-Nov-202160.9 KiB1,124865

json.hppH A D16-Nov-2021955.6 KiB26,64115,533

README.md

1[![JSON for Modern C++](https://raw.githubusercontent.com/nlohmann/json/master/doc/json.gif)](https://github.com/nlohmann/json/releases)
2
3[![Build Status](https://travis-ci.org/nlohmann/json.svg?branch=master)](https://travis-ci.org/nlohmann/json)
4[![Build Status](https://ci.appveyor.com/api/projects/status/1acb366xfyg3qybk/branch/develop?svg=true)](https://ci.appveyor.com/project/nlohmann/json)
5[![Coverage Status](https://img.shields.io/coveralls/nlohmann/json.svg)](https://coveralls.io/r/nlohmann/json)
6[![Coverity Scan Build Status](https://scan.coverity.com/projects/5550/badge.svg)](https://scan.coverity.com/projects/nlohmann-json)
7[![Codacy Badge](https://api.codacy.com/project/badge/Grade/f3732b3327e34358a0e9d1fe9f661f08)](https://www.codacy.com/app/nlohmann/json?utm_source=github.com&utm_medium=referral&utm_content=nlohmann/json&utm_campaign=Badge_Grade)
8[![Try online](https://img.shields.io/badge/try-online-blue.svg)](https://wandbox.org/permlink/TarF5pPn9NtHQjhf)
9[![Documentation](https://img.shields.io/badge/docs-doxygen-blue.svg)](http://nlohmann.github.io/json)
10[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/nlohmann/json/master/LICENSE.MIT)
11[![GitHub Releases](https://img.shields.io/github/release/nlohmann/json.svg)](https://github.com/nlohmann/json/releases)
12[![GitHub Issues](https://img.shields.io/github/issues/nlohmann/json.svg)](http://github.com/nlohmann/json/issues)
13[![Average time to resolve an issue](http://isitmaintained.com/badge/resolution/nlohmann/json.svg)](http://isitmaintained.com/project/nlohmann/json "Average time to resolve an issue")
14[![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/289/badge)](https://bestpractices.coreinfrastructure.org/projects/289)
15
16- [Design goals](#design-goals)
17- [Integration](#integration)
18- [Examples](#examples)
19  - [JSON as first-class data type](#json-as-first-class-data-type)
20  - [Serialization / Deserialization](#serialization--deserialization)
21  - [STL-like access](#stl-like-access)
22  - [Conversion from STL containers](#conversion-from-stl-containers)
23  - [JSON Pointer and JSON Patch](#json-pointer-and-json-patch)
24  - [JSON Merge Patch](#json-merge-patch)
25  - [Implicit conversions](#implicit-conversions)
26  - [Conversions to/from arbitrary types](#arbitrary-types-conversions)
27  - [Binary formats (CBOR, MessagePack, and UBJSON)](#binary-formats-cbor-messagepack-and-ubjson)
28- [Supported compilers](#supported-compilers)
29- [License](#license)
30- [Contact](#contact)
31- [Thanks](#thanks)
32- [Used third-party tools](#used-third-party-tools)
33- [Projects using JSON for Modern C++](#projects-using-json-for-modern-c)
34- [Notes](#notes)
35- [Execute unit tests](#execute-unit-tests)
36
37## Design goals
38
39There are myriads of [JSON](http://json.org) libraries out there, and each may even have its reason to exist. Our class had these design goals:
40
41- **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](#examples) and you'll know what I mean.
42
43- **Trivial integration**. Our whole code consists of a single header file [`json.hpp`](https://github.com/nlohmann/json/blob/develop/single_include/nlohmann/json.hpp). 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.
44
45- **Serious testing**. Our class is heavily [unit-tested](https://github.com/nlohmann/json/tree/develop/test/src) and covers [100%](https://coveralls.io/r/nlohmann/json) of the code, including all exceptional behavior. Furthermore, we checked with [Valgrind](http://valgrind.org) and the [Clang Sanitizers](https://clang.llvm.org/docs/index.html) that there are no memory leaks. [Google OSS-Fuzz](https://github.com/google/oss-fuzz/tree/master/projects/json) additionally runs fuzz tests agains 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](https://bestpractices.coreinfrastructure.org/projects/289).
46
47Other aspects were not so important to us:
48
49- **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::string` for strings, `int64_t`, `uint64_t` or `double` for numbers, `std::map` for objects, `std::vector` for arrays, and `bool` for Booleans. However, you can template the generalized class `basic_json` to your needs.
50
51- **Speed**. There are certainly [faster JSON libraries](https://github.com/miloyip/nativejson-benchmark#parsing-time) 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::vector` or `std::map`, you are already set.
52
53See the [contribution guidelines](https://github.com/nlohmann/json/blob/master/.github/CONTRIBUTING.md#please-dont) for more information.
54
55
56## Integration
57
58[`json.hpp`](https://github.com/nlohmann/json/blob/develop/single_include/nlohmann/json.hpp) is the single required file in `single_include/nlohmann` or [released here](https://github.com/nlohmann/json/releases). You need to add
59
60```cpp
61#include <nlohmann/json.hpp>
62
63// for convenience
64using json = nlohmann::json;
65```
66
67to the files you want to process JSON and set the necessary switches to enable C++11 (e.g., `-std=c++11` for GCC and Clang).
68
69You can further use file [`include/nlohmann/json_fwd.hpp`](https://github.com/nlohmann/json/blob/develop/include/nlohmann/json_fwd.hpp) for forward-declarations. The installation of json_fwd.hpp (as part of cmake's install step), can be achieved by setting `-DJSON_MultipleHeaders=ON`.
70
71### Package Managers
72
73:beer: If you are using OS X and [Homebrew](http://brew.sh), just type `brew tap nlohmann/json` and `brew install nlohmann_json` and you're set. If you want the bleeding edge rather than the latest release, use `brew install nlohmann_json --HEAD`.
74
75If you are using the [Meson Build System](http://mesonbuild.com), then you can wrap this repository as a subproject.
76
77If you are using [Conan](https://www.conan.io/) to manage your dependencies, merely add `jsonformoderncpp/x.y.z@vthiery/stable` to your `conanfile.py`'s requires, where `x.y.z` is the release version you want to use. Please file issues [here](https://github.com/vthiery/conan-jsonformoderncpp/issues) if you experience problems with the packages.
78
79If you are using [Spack](https://www.spack.io/) to manage your dependencies, you can use the `nlohmann_json` package. Please see the [spack project](https://github.com/spack/spack) for any issues regarding the packaging.
80
81If you are using [hunter](https://github.com/ruslo/hunter/) on your project for external dependencies, then you can use the [nlohmann_json package](https://docs.hunter.sh/en/latest/packages/pkg/nlohmann_json.html). Please see the hunter project for any issues regarding the packaging.
82
83If you are using [Buckaroo](https://buckaroo.pm), you can install this library's module with `buckaroo install nlohmann/json`. Please file issues [here](https://github.com/LoopPerfect/buckaroo-recipes/issues/new?title=nlohmann/nlohmann/json).
84
85If you are using [vcpkg](https://github.com/Microsoft/vcpkg/) on your project for external dependencies, then you can use the [nlohmann-json package](https://github.com/Microsoft/vcpkg/tree/master/ports/nlohmann-json). Please see the vcpkg project for any issues regarding the packaging.
86
87If you are using [cget](http://cget.readthedocs.io/en/latest/), you can install the latest development version with `cget install nlohmann/json`. A specific version can be installed with `cget install nlohmann/json@v3.1.0`. Also, the multiple header version can be installed by adding the `-DJSON_MultipleHeaders=ON` flag (i.e., `cget install nlohmann/json -DJSON_MultipleHeaders=ON`).
88
89If you are using [CocoaPods](https://cocoapods.org), you can use the library by adding pod `"nlohmann_json", '~>3.1.2'` to your podfile (see [an example](https://bitbucket.org/benman/nlohmann_json-cocoapod/src/master/)). Please file issues [here](https://bitbucket.org/benman/nlohmann_json-cocoapod/issues?status=new&status=open).
90
91## Examples
92
93Beside the examples below, you may want to check the [documentation](https://nlohmann.github.io/json/) where each function contains a separate code example (e.g., check out [`emplace()`](https://nlohmann.github.io/json/classnlohmann_1_1basic__json_a5338e282d1d02bed389d852dd670d98d.html#a5338e282d1d02bed389d852dd670d98d)). All [example files](https://github.com/nlohmann/json/tree/develop/doc/examples) can be compiled and executed on their own (e.g., file [emplace.cpp](https://github.com/nlohmann/json/blob/develop/doc/examples/emplace.cpp)).
94
95### JSON as first-class data type
96
97Here are some examples to give you an idea how to use the class.
98
99Assume you want to create the JSON object
100
101```json
102{
103  "pi": 3.141,
104  "happy": true,
105  "name": "Niels",
106  "nothing": null,
107  "answer": {
108    "everything": 42
109  },
110  "list": [1, 0, 2],
111  "object": {
112    "currency": "USD",
113    "value": 42.99
114  }
115}
116```
117
118With this library, you could write:
119
120```cpp
121// create an empty structure (null)
122json j;
123
124// add a number that is stored as double (note the implicit conversion of j to an object)
125j["pi"] = 3.141;
126
127// add a Boolean that is stored as bool
128j["happy"] = true;
129
130// add a string that is stored as std::string
131j["name"] = "Niels";
132
133// add another null object by passing nullptr
134j["nothing"] = nullptr;
135
136// add an object inside the object
137j["answer"]["everything"] = 42;
138
139// add an array that is stored as std::vector (using an initializer list)
140j["list"] = { 1, 0, 2 };
141
142// add another object (using an initializer list of pairs)
143j["object"] = { {"currency", "USD"}, {"value", 42.99} };
144
145// instead, you could also write (which looks very similar to the JSON above)
146json j2 = {
147  {"pi", 3.141},
148  {"happy", true},
149  {"name", "Niels"},
150  {"nothing", nullptr},
151  {"answer", {
152    {"everything", 42}
153  }},
154  {"list", {1, 0, 2}},
155  {"object", {
156    {"currency", "USD"},
157    {"value", 42.99}
158  }}
159};
160```
161
162Note 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 [`json::array`](https://nlohmann.github.io/json/classnlohmann_1_1basic__json_aa80485befaffcadaa39965494e0b4d2e.html#aa80485befaffcadaa39965494e0b4d2e) and [`json::object`](https://nlohmann.github.io/json/classnlohmann_1_1basic__json_aa13f7c0615867542ce80337cbcf13ada.html#aa13f7c0615867542ce80337cbcf13ada) will help:
163
164```cpp
165// a way to express the empty array []
166json empty_array_explicit = json::array();
167
168// ways to express the empty object {}
169json empty_object_implicit = json({});
170json empty_object_explicit = json::object();
171
172// a way to express an _array_ of key/value pairs [["currency", "USD"], ["value", 42.99]]
173json array_not_object = json::array({ {"currency", "USD"}, {"value", 42.99} });
174```
175
176### Serialization / Deserialization
177
178#### To/from strings
179
180You can create a JSON value (deserialization) by appending `_json` to a string literal:
181
182```cpp
183// create object from string literal
184json j = "{ \"happy\": true, \"pi\": 3.141 }"_json;
185
186// or even nicer with a raw string literal
187auto j2 = R"(
188  {
189    "happy": true,
190    "pi": 3.141
191  }
192)"_json;
193```
194
195Note 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.
196
197The above example can also be expressed explicitly using [`json::parse()`](https://nlohmann.github.io/json/classnlohmann_1_1basic__json_aa9676414f2e36383c4b181fe856aa3c0.html#aa9676414f2e36383c4b181fe856aa3c0):
198
199```cpp
200// parse explicitly
201auto j3 = json::parse("{ \"happy\": true, \"pi\": 3.141 }");
202```
203
204You can also get a string representation of a JSON value (serialize):
205
206```cpp
207// explicit conversion to string
208std::string s = j.dump();    // {\"happy\":true,\"pi\":3.141}
209
210// serialization with pretty printing
211// pass in the amount of spaces to indent
212std::cout << j.dump(4) << std::endl;
213// {
214//     "happy": true,
215//     "pi": 3.141
216// }
217```
218
219Note the difference between serialization and assignment:
220
221```cpp
222// store a string in a JSON value
223json j_string = "this is a string";
224
225// retrieve the string value (implicit JSON to std::string conversion)
226std::string cpp_string = j_string;
227// retrieve the string value (explicit JSON to std::string conversion)
228auto cpp_string2 = j_string.get<std::string>();
229
230// retrieve the serialized value (explicit JSON serialization)
231std::string serialized_string = j_string.dump();
232
233// output of original string
234std::cout << cpp_string << " == " << cpp_string2 << " == " << j_string.get<std::string>() << '\n';
235// output of serialized value
236std::cout << j_string << " == " << serialized_string << std::endl;
237```
238
239[`.dump()`](https://nlohmann.github.io/json/classnlohmann_1_1basic__json_a5adea76fedba9898d404fef8598aa663.html#a5adea76fedba9898d404fef8598aa663) always returns the serialized value, and [`.get<std::string>()`](https://nlohmann.github.io/json/classnlohmann_1_1basic__json_a16f9445f7629f634221a42b967cdcd43.html#a16f9445f7629f634221a42b967cdcd43) returns the originally stored string value.
240
241Note the library only supports UTF-8. When you store strings with different encodings in the library, calling [`dump()`](https://nlohmann.github.io/json/classnlohmann_1_1basic__json_a5adea76fedba9898d404fef8598aa663.html#a5adea76fedba9898d404fef8598aa663) may throw an exception.
242
243#### To/from streams (e.g. files, string streams)
244
245You can also use streams to serialize and deserialize:
246
247```cpp
248// deserialize from standard input
249json j;
250std::cin >> j;
251
252// serialize to standard output
253std::cout << j;
254
255// the setw manipulator was overloaded to set the indentation for pretty printing
256std::cout << std::setw(4) << j << std::endl;
257```
258
259These operators work for any subclasses of `std::istream` or `std::ostream`. Here is the same example with files:
260
261```cpp
262// read a JSON file
263std::ifstream i("file.json");
264json j;
265i >> j;
266
267// write prettified JSON to another file
268std::ofstream o("pretty.json");
269o << std::setw(4) << j << std::endl;
270```
271
272Please 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.
273
274#### Read from iterator range
275
276You can also parse JSON from an iterator range; that is, from any container accessible by iterators whose content is stored as contiguous byte sequence, for instance a `std::vector<std::uint8_t>`:
277
278```cpp
279std::vector<std::uint8_t> v = {'t', 'r', 'u', 'e'};
280json j = json::parse(v.begin(), v.end());
281```
282
283You may leave the iterators for the range [begin, end):
284
285```cpp
286std::vector<std::uint8_t> v = {'t', 'r', 'u', 'e'};
287json j = json::parse(v);
288```
289
290#### SAX interface
291
292The library uses a SAX-like interface with the following functions:
293
294```cpp
295// called when null is parsed
296bool null();
297
298// called when a boolean is parsed; value is passed
299bool boolean(bool val);
300
301// called when a signed or unsigned integer number is parsed; value is passed
302bool number_integer(number_integer_t val);
303bool number_unsigned(number_unsigned_t val);
304
305// called when a floating-point number is parsed; value and original string is passed
306bool number_float(number_float_t val, const string_t& s);
307
308// called when a string is parsed; value is passed and can be safely moved away
309bool string(string_t& val);
310
311// called when an object or array begins or ends, resp. The number of elements is passed (or -1 if not known)
312bool start_object(std::size_t elements);
313bool end_object();
314bool start_array(std::size_t elements);
315bool end_array();
316// called when an object key is parsed; value is passed and can be safely moved away
317bool key(string_t& val);
318
319// called when a parse error occurs; byte position, the last token, and an exception is passed
320bool parse_error(std::size_t position, const std::string& last_token, const detail::exception& ex);
321```
322
323The return value of each function determines whether parsing should proceed.
324
325To implement your own SAX handler, proceed as follows:
326
3271. 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.
3282. Create an object of your SAX interface class, e.g. `my_sax`.
3293. 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.
330
331Note 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 [`json_sax.hpp`](https://github.com/nlohmann/json/blob/develop/include/nlohmann/detail/input/json_sax.hpp).
332
333
334### STL-like access
335
336We designed the JSON class to behave just like an STL container. In fact, it satisfies the [**ReversibleContainer**](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer) requirement.
337
338```cpp
339// create an array using push_back
340json j;
341j.push_back("foo");
342j.push_back(1);
343j.push_back(true);
344
345// also use emplace_back
346j.emplace_back(1.78);
347
348// iterate the array
349for (json::iterator it = j.begin(); it != j.end(); ++it) {
350  std::cout << *it << '\n';
351}
352
353// range-based for
354for (auto& element : j) {
355  std::cout << element << '\n';
356}
357
358// getter/setter
359const std::string tmp = j[0];
360j[1] = 42;
361bool foo = j.at(2);
362
363// comparison
364j == "[\"foo\", 1, true]"_json;  // true
365
366// other stuff
367j.size();     // 3 entries
368j.empty();    // false
369j.type();     // json::value_t::array
370j.clear();    // the array is empty again
371
372// convenience type checkers
373j.is_null();
374j.is_boolean();
375j.is_number();
376j.is_object();
377j.is_array();
378j.is_string();
379
380// create an object
381json o;
382o["foo"] = 23;
383o["bar"] = false;
384o["baz"] = 3.141;
385
386// also use emplace
387o.emplace("weather", "sunny");
388
389// special iterator member functions for objects
390for (json::iterator it = o.begin(); it != o.end(); ++it) {
391  std::cout << it.key() << " : " << it.value() << "\n";
392}
393
394// find an entry
395if (o.find("foo") != o.end()) {
396  // there is an entry with key "foo"
397}
398
399// or simpler using count()
400int foo_present = o.count("foo"); // 1
401int fob_present = o.count("fob"); // 0
402
403// delete an entry
404o.erase("foo");
405```
406
407
408### Conversion from STL containers
409
410Any 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.
411
412```cpp
413std::vector<int> c_vector {1, 2, 3, 4};
414json j_vec(c_vector);
415// [1, 2, 3, 4]
416
417std::deque<double> c_deque {1.2, 2.3, 3.4, 5.6};
418json j_deque(c_deque);
419// [1.2, 2.3, 3.4, 5.6]
420
421std::list<bool> c_list {true, true, false, true};
422json j_list(c_list);
423// [true, true, false, true]
424
425std::forward_list<int64_t> c_flist {12345678909876, 23456789098765, 34567890987654, 45678909876543};
426json j_flist(c_flist);
427// [12345678909876, 23456789098765, 34567890987654, 45678909876543]
428
429std::array<unsigned long, 4> c_array {{1, 2, 3, 4}};
430json j_array(c_array);
431// [1, 2, 3, 4]
432
433std::set<std::string> c_set {"one", "two", "three", "four", "one"};
434json j_set(c_set); // only one entry for "one" is used
435// ["four", "one", "three", "two"]
436
437std::unordered_set<std::string> c_uset {"one", "two", "three", "four", "one"};
438json j_uset(c_uset); // only one entry for "one" is used
439// maybe ["two", "three", "four", "one"]
440
441std::multiset<std::string> c_mset {"one", "two", "one", "four"};
442json j_mset(c_mset); // both entries for "one" are used
443// maybe ["one", "two", "one", "four"]
444
445std::unordered_multiset<std::string> c_umset {"one", "two", "one", "four"};
446json j_umset(c_umset); // both entries for "one" are used
447// maybe ["one", "two", "one", "four"]
448```
449
450Likewise, 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.
451
452```cpp
453std::map<std::string, int> c_map { {"one", 1}, {"two", 2}, {"three", 3} };
454json j_map(c_map);
455// {"one": 1, "three": 3, "two": 2 }
456
457std::unordered_map<const char*, double> c_umap { {"one", 1.2}, {"two", 2.3}, {"three", 3.4} };
458json j_umap(c_umap);
459// {"one": 1.2, "two": 2.3, "three": 3.4}
460
461std::multimap<std::string, bool> c_mmap { {"one", true}, {"two", true}, {"three", false}, {"three", true} };
462json j_mmap(c_mmap); // only one entry for key "three" is used
463// maybe {"one": true, "two": true, "three": true}
464
465std::unordered_multimap<std::string, bool> c_ummap { {"one", true}, {"two", true}, {"three", false}, {"three", true} };
466json j_ummap(c_ummap); // only one entry for key "three" is used
467// maybe {"one": true, "two": true, "three": true}
468```
469
470### JSON Pointer and JSON Patch
471
472The library supports **JSON Pointer** ([RFC 6901](https://tools.ietf.org/html/rfc6901)) as alternative means to address structured values. On top of this, **JSON Patch** ([RFC 6902](https://tools.ietf.org/html/rfc6902)) allows to describe differences between two JSON values - effectively allowing patch and diff operations known from Unix.
473
474```cpp
475// a JSON value
476json j_original = R"({
477  "baz": ["one", "two", "three"],
478  "foo": "bar"
479})"_json;
480
481// access members with a JSON pointer (RFC 6901)
482j_original["/baz/1"_json_pointer];
483// "two"
484
485// a JSON patch (RFC 6902)
486json j_patch = R"([
487  { "op": "replace", "path": "/baz", "value": "boo" },
488  { "op": "add", "path": "/hello", "value": ["world"] },
489  { "op": "remove", "path": "/foo"}
490])"_json;
491
492// apply the patch
493json j_result = j_original.patch(j_patch);
494// {
495//    "baz": "boo",
496//    "hello": ["world"]
497// }
498
499// calculate a JSON patch from two JSON values
500json::diff(j_result, j_original);
501// [
502//   { "op":" replace", "path": "/baz", "value": ["one", "two", "three"] },
503//   { "op": "remove","path": "/hello" },
504//   { "op": "add", "path": "/foo", "value": "bar" }
505// ]
506```
507
508### JSON Merge Patch
509
510The library supports **JSON Merge Patch** ([RFC 7386](https://tools.ietf.org/html/rfc7386)) 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.
511
512```cpp
513// a JSON value
514json j_document = R"({
515  "a": "b",
516  "c": {
517    "d": "e",
518    "f": "g"
519  }
520})"_json;
521
522// a patch
523json j_patch = R"({
524  "a":"z",
525  "c": {
526    "f": null
527  }
528})"_json;
529
530// apply the patch
531j_original.merge_patch(j_patch);
532// {
533//  "a": "z",
534//  "c": {
535//    "d": "e"
536//  }
537// }
538```
539
540### Implicit conversions
541
542The type of the JSON object is determined automatically by the expression to store. Likewise, the stored value is implicitly converted.
543
544```cpp
545// strings
546std::string s1 = "Hello, world!";
547json js = s1;
548std::string s2 = js;
549
550// Booleans
551bool b1 = true;
552json jb = b1;
553bool b2 = jb;
554
555// numbers
556int i = 42;
557json jn = i;
558double f = jn;
559
560// etc.
561```
562
563You can also explicitly ask for the value:
564
565```cpp
566std::string vs = js.get<std::string>();
567bool vb = jb.get<bool>();
568int vi = jn.get<int>();
569
570// etc.
571```
572
573Note that `char` types are not automatically converted to JSON strings, but to integer numbers. A conversion to a string must be specified explicitly:
574
575```cpp
576char ch = 'A';                       // ASCII value 65
577json j_default = ch;                 // stores integer number 65
578json j_string = std::string(1, ch);  // stores string "A"
579```
580
581### Arbitrary types conversions
582
583Every type can be serialized in JSON, not just STL containers and scalar types. Usually, you would do something along those lines:
584
585```cpp
586namespace ns {
587    // a simple struct to model a person
588    struct person {
589        std::string name;
590        std::string address;
591        int age;
592    };
593}
594
595ns::person p = {"Ned Flanders", "744 Evergreen Terrace", 60};
596
597// convert to JSON: copy each value into the JSON object
598json j;
599j["name"] = p.name;
600j["address"] = p.address;
601j["age"] = p.age;
602
603// ...
604
605// convert from JSON: copy each value from the JSON object
606ns::person p {
607    j["name"].get<std::string>(),
608    j["address"].get<std::string>(),
609    j["age"].get<int>()
610};
611```
612
613It works, but that's quite a lot of boilerplate... Fortunately, there's a better way:
614
615```cpp
616// create a person
617ns::person p {"Ned Flanders", "744 Evergreen Terrace", 60};
618
619// conversion: person -> json
620json j = p;
621
622std::cout << j << std::endl;
623// {"address":"744 Evergreen Terrace","age":60,"name":"Ned Flanders"}
624
625// conversion: json -> person
626ns::person p2 = j;
627
628// that's it
629assert(p == p2);
630```
631
632#### Basic usage
633
634To make this work with one of your types, you only need to provide two functions:
635
636```cpp
637using nlohmann::json;
638
639namespace ns {
640    void to_json(json& j, const person& p) {
641        j = json{{"name", p.name}, {"address", p.address}, {"age", p.age}};
642    }
643
644    void from_json(const json& j, person& p) {
645        p.name = j.at("name").get<std::string>();
646        p.address = j.at("address").get<std::string>();
647        p.age = j.at("age").get<int>();
648    }
649} // namespace ns
650```
651
652That's all! When calling the `json` constructor with your type, your custom `to_json` method will be automatically called.
653Likewise, when calling `get<your_type>()`, the `from_json` method will be called.
654
655Some important things:
656
657* 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`, where `person` is defined).
658* Those methods **MUST** be available (e.g., properly headers must be included) everywhere you use the implicit conversions. Look at [issue 1108](https://github.com/nlohmann/json/issues/1108) for errors that may occur otherwise.
659* When using `get<your_type>()`, `your_type` **MUST** be [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). (There is a way to bypass this requirement described later.)
660* In function `from_json`, use function [`at()`](https://nlohmann.github.io/json/classnlohmann_1_1basic__json_a93403e803947b86f4da2d1fb3345cf2c.html#a93403e803947b86f4da2d1fb3345cf2c) to access the object values rather than `operator[]`. In case a key does not exist, `at` throws an exception that you can handle, whereas `operator[]` exhibits undefined behavior.
661* In case your type contains several `operator=` definitions, code like `your_variable = your_json;` [may not compile](https://github.com/nlohmann/json/issues/667). You need to write `your_variable = your_json.get<decltype your_variable>();` instead.
662* You do not need to add serializers or deserializers for STL types like `std::vector`: the library already implements these.
663* Be careful with the definition order of the `from_json`/`to_json` functions: If a type `B` has a member of type `A`, you **MUST** define `to_json(A)` before `to_json(B)`. Look at [issue 561](https://github.com/nlohmann/json/issues/561) for more details.
664
665
666#### How do I convert third-party types?
667
668This requires a bit more advanced technique. But first, let's see how this conversion mechanism works:
669
670The library uses **JSON Serializers** to convert types to json.
671The default serializer for `nlohmann::json` is `nlohmann::adl_serializer` (ADL means [Argument-Dependent Lookup](https://en.cppreference.com/w/cpp/language/adl)).
672
673It is implemented like this (simplified):
674
675```cpp
676template <typename T>
677struct adl_serializer {
678    static void to_json(json& j, const T& value) {
679        // calls the "to_json" method in T's namespace
680    }
681
682    static void from_json(const json& j, T& value) {
683        // same thing, but with the "from_json" method
684    }
685};
686```
687
688This 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`...
689
690To solve this, you need to add a specialization of `adl_serializer` to the `nlohmann` namespace, here's an example:
691
692```cpp
693// partial specialization (full specialization works too)
694namespace nlohmann {
695    template <typename T>
696    struct adl_serializer<boost::optional<T>> {
697        static void to_json(json& j, const boost::optional<T>& opt) {
698            if (opt == boost::none) {
699                j = nullptr;
700            } else {
701              j = *opt; // this will call adl_serializer<T>::to_json which will
702                        // find the free function to_json in T's namespace!
703            }
704        }
705
706        static void from_json(const json& j, boost::optional<T>& opt) {
707            if (j.is_null()) {
708                opt = boost::none;
709            } else {
710                opt = j.get<T>(); // same as above, but with
711                                  // adl_serializer<T>::from_json
712            }
713        }
714    };
715}
716```
717
718#### How can I use `get()` for non-default constructible/non-copyable types?
719
720There is a way, if your type is [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible). You will need to specialize the `adl_serializer` as well, but with a special `from_json` overload:
721
722```cpp
723struct move_only_type {
724    move_only_type() = delete;
725    move_only_type(int ii): i(ii) {}
726    move_only_type(const move_only_type&) = delete;
727    move_only_type(move_only_type&&) = default;
728
729    int i;
730};
731
732namespace nlohmann {
733    template <>
734    struct adl_serializer<move_only_type> {
735        // note: the return type is no longer 'void', and the method only takes
736        // one argument
737        static move_only_type from_json(const json& j) {
738            return {j.get<int>()};
739        }
740
741        // Here's the catch! You must provide a to_json method! Otherwise you
742        // will not be able to convert move_only_type to json, since you fully
743        // specialized adl_serializer on that type
744        static void to_json(json& j, move_only_type t) {
745            j = t.i;
746        }
747    };
748}
749```
750
751#### Can I write my own serializer? (Advanced use)
752
753Yes. You might want to take a look at [`unit-udt.cpp`](https://github.com/nlohmann/json/blob/develop/test/src/unit-udt.cpp) in the test suite, to see a few examples.
754
755If you write your own serializer, you'll need to do a few things:
756
757- use a different `basic_json` alias than `nlohmann::json` (the last template parameter of `basic_json` is the `JSONSerializer`)
758- use your `basic_json` alias (or a template parameter) in all your `to_json`/`from_json` methods
759- use `nlohmann::to_json` and `nlohmann::from_json` when you need ADL
760
761Here is an example, without simplifications, that only accepts types with a size <= 32, and uses ADL.
762
763```cpp
764// You should use void as a second template argument
765// if you don't need compile-time checks on T
766template<typename T, typename SFINAE = typename std::enable_if<sizeof(T) <= 32>::type>
767struct less_than_32_serializer {
768    template <typename BasicJsonType>
769    static void to_json(BasicJsonType& j, T value) {
770        // we want to use ADL, and call the correct to_json overload
771        using nlohmann::to_json; // this method is called by adl_serializer,
772                                 // this is where the magic happens
773        to_json(j, value);
774    }
775
776    template <typename BasicJsonType>
777    static void from_json(const BasicJsonType& j, T& value) {
778        // same thing here
779        using nlohmann::from_json;
780        from_json(j, value);
781    }
782};
783```
784
785Be **very** careful when reimplementing your serializer, you can stack overflow if you don't pay attention:
786
787```cpp
788template <typename T, void>
789struct bad_serializer
790{
791    template <typename BasicJsonType>
792    static void to_json(BasicJsonType& j, const T& value) {
793      // this calls BasicJsonType::json_serializer<T>::to_json(j, value);
794      // if BasicJsonType::json_serializer == bad_serializer ... oops!
795      j = value;
796    }
797
798    template <typename BasicJsonType>
799    static void to_json(const BasicJsonType& j, T& value) {
800      // this calls BasicJsonType::json_serializer<T>::from_json(j, value);
801      // if BasicJsonType::json_serializer == bad_serializer ... oops!
802      value = j.template get<T>(); // oops!
803    }
804};
805```
806
807### Binary formats (CBOR, MessagePack, and UBJSON)
808
809Though 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 [CBOR](http://cbor.io) (Concise Binary Object Representation), [MessagePack](http://msgpack.org), and [UBJSON](http://ubjson.org) (Universal Binary JSON Specification) to efficiently encode JSON values to byte vectors and to decode such vectors.
810
811```cpp
812// create a JSON value
813json j = R"({"compact": true, "schema": 0})"_json;
814
815// serialize to CBOR
816std::vector<std::uint8_t> v_cbor = json::to_cbor(j);
817
818// 0xA2, 0x67, 0x63, 0x6F, 0x6D, 0x70, 0x61, 0x63, 0x74, 0xF5, 0x66, 0x73, 0x63, 0x68, 0x65, 0x6D, 0x61, 0x00
819
820// roundtrip
821json j_from_cbor = json::from_cbor(v_cbor);
822
823// serialize to MessagePack
824std::vector<std::uint8_t> v_msgpack = json::to_msgpack(j);
825
826// 0x82, 0xA7, 0x63, 0x6F, 0x6D, 0x70, 0x61, 0x63, 0x74, 0xC3, 0xA6, 0x73, 0x63, 0x68, 0x65, 0x6D, 0x61, 0x00
827
828// roundtrip
829json j_from_msgpack = json::from_msgpack(v_msgpack);
830
831// serialize to UBJSON
832std::vector<std::uint8_t> v_ubjson = json::to_ubjson(j);
833
834// 0x7B, 0x69, 0x07, 0x63, 0x6F, 0x6D, 0x70, 0x61, 0x63, 0x74, 0x54, 0x69, 0x06, 0x73, 0x63, 0x68, 0x65, 0x6D, 0x61, 0x69, 0x00, 0x7D
835
836// roundtrip
837json j_from_ubjson = json::from_ubjson(v_ubjson);
838```
839
840
841## Supported compilers
842
843Though it's 2018 already, the support for C++11 is still a bit sparse. Currently, the following compilers are known to work:
844
845- GCC 4.9 - 8.2 (and possibly later)
846- Clang 3.4 - 6.1 (and possibly later)
847- Intel C++ Compiler 17.0.2 (and possibly later)
848- Microsoft Visual C++ 2015 / Build Tools 14.0.25123.0 (and possibly later)
849- Microsoft Visual C++ 2017 / Build Tools 15.5.180.51428 (and possibly later)
850
851I would be happy to learn about other compilers/versions.
852
853Please note:
854
855- GCC 4.8 does not work because of two bugs ([55817](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=55817) and [57824](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=57824)) in the C++11 support. Note there is a [pull request](https://github.com/nlohmann/json/pull/212) to fix some of the issues.
856- Android defaults to using very old compilers and C++ libraries. To fix this, add the following to your `Application.mk`. This will switch to the LLVM C++ library, the Clang compiler, and enable C++11 and other features disabled by default.
857
858    ```
859    APP_STL := c++_shared
860    NDK_TOOLCHAIN_VERSION := clang3.6
861    APP_CPPFLAGS += -frtti -fexceptions
862    ```
863
864    The code compiles successfully with [Android NDK](https://developer.android.com/ndk/index.html?hl=ml), Revision 9 - 11 (and possibly later) and [CrystaX's Android NDK](https://www.crystax.net/en/android/ndk) version 10.
865
866- For GCC running on MinGW or Android SDK, the error `'to_string' is not a member of 'std'` (or similarly, for `strtod`) may occur. Note this is not an issue with the code,  but rather with the compiler itself. On Android, see above to build with a newer environment.  For MinGW, please refer to [this site](http://tehsausage.com/mingw-to-string) and [this discussion](https://github.com/nlohmann/json/issues/136) for information on how to fix this bug. For Android NDK using `APP_STL := gnustl_static`, please refer to [this discussion](https://github.com/nlohmann/json/issues/219).
867
868- Unsupported versions of GCC and Clang are rejected by `#error` directives. This can be switched off by defining `JSON_SKIP_UNSUPPORTED_COMPILER_CHECK`. Note that you can expect no support in this case.
869
870The following compilers are currently used in continuous integration at [Travis](https://travis-ci.org/nlohmann/json) and [AppVeyor](https://ci.appveyor.com/project/nlohmann/json):
871
872| Compiler        | Operating System             | Version String |
873|-----------------|------------------------------|----------------|
874| GCC 4.9.4       | Ubuntu 14.04.1 LTS           | g++-4.9 (Ubuntu 4.9.4-2ubuntu1~14.04.1) 4.9.4 |
875| GCC 5.5.0       | Ubuntu 14.04.1 LTS           | g++-5 (Ubuntu 5.5.0-12ubuntu1~14.04) 5.5.0 20171010 |
876| GCC 6.4.0       | Ubuntu 14.04.1 LTS           | g++-6 (Ubuntu 6.4.0-17ubuntu1~14.04) 6.4.0 20180424 |
877| GCC 7.3.0       | Ubuntu 14.04.1 LTS           | g++-7 (Ubuntu 7.3.0-21ubuntu1~14.04) 7.3.0 |
878| GCC 7.3.0       | Windows Server 2012 R2 (x64) | g++ (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 7.3.0 |
879| GCC 8.1.0       | Ubuntu 14.04.1 LTS           | g++-8 (Ubuntu 8.1.0-5ubuntu1~14.04) 8.1.0 |
880| Clang 3.5.0     | Ubuntu 14.04.1 LTS           | clang version 3.5.0-4ubuntu2~trusty2 (tags/RELEASE_350/final) (based on LLVM 3.5.0) |
881| Clang 3.6.2     | Ubuntu 14.04.1 LTS           | clang version 3.6.2-svn240577-1~exp1 (branches/release_36) (based on LLVM 3.6.2) |
882| Clang 3.7.1     | Ubuntu 14.04.1 LTS           | clang version 3.7.1-svn253571-1~exp1 (branches/release_37) (based on LLVM 3.7.1) |
883| Clang 3.8.0     | Ubuntu 14.04.1 LTS           | clang version 3.8.0-2ubuntu3~trusty5 (tags/RELEASE_380/final) |
884| Clang 3.9.1     | Ubuntu 14.04.1 LTS           | clang version 3.9.1-4ubuntu3~14.04.3 (tags/RELEASE_391/rc2) |
885| Clang 4.0.1     | Ubuntu 14.04.1 LTS           | clang version 4.0.1-svn305264-1~exp1 (branches/release_40) |
886| Clang 5.0.2     | Ubuntu 14.04.1 LTS           | clang version 5.0.2-svn328729-1~exp1~20180509123505.100 (branches/release_50) |
887| Clang 6.0.1     | Ubuntu 14.04.1 LTS           | clang version 6.0.1-svn334776-1~exp1~20180726133705.85 (branches/release_60) |
888| Clang Xcode 6.4 | OSX 10.10.5 | Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn) |
889| Clang Xcode 7.3 | OSX 10.11.6 | Apple LLVM version 7.3.0 (clang-703.0.31) |
890| Clang Xcode 8.0 | OSX 10.11.6 | Apple LLVM version 8.0.0 (clang-800.0.38) |
891| Clang Xcode 8.1 | OSX 10.12.6 | Apple LLVM version 8.0.0 (clang-800.0.42.1) |
892| Clang Xcode 8.2 | OSX 10.12.6 | Apple LLVM version 8.0.0 (clang-800.0.42.1) |
893| Clang Xcode 8.3 | OSX 10.11.6 | Apple LLVM version 8.1.0 (clang-802.0.38) |
894| Clang Xcode 9.0 | OSX 10.12.6 | Apple LLVM version 9.0.0 (clang-900.0.37) |
895| Clang Xcode 9.1 | OSX 10.12.6 | Apple LLVM version 9.0.0 (clang-900.0.38) |
896| Clang Xcode 9.2 | OSX 10.13.3 | Apple LLVM version 9.1.0 (clang-902.0.39.1) |
897| Clang Xcode 9.3 | OSX 10.13.3 | Apple LLVM version 9.1.0 (clang-902.0.39.2) |
898| Visual Studio 14 2015 | Windows Server 2012 R2 (x64) | Microsoft (R) Build Engine version 14.0.25420.1, MSVC 19.0.24215.1 |
899| Visual Studio 2017 | Windows Server 2016 | Microsoft (R) Build Engine version 15.7.180.61344, MSVC 19.14.26433.0 |
900
901## License
902
903<img align="right" src="http://opensource.org/trademarks/opensource/OSI-Approved-License-100x137.png">
904
905The class is licensed under the [MIT License](http://opensource.org/licenses/MIT):
906
907Copyright &copy; 2013-2018 [Niels Lohmann](http://nlohmann.me)
908
909Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
910
911The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
912
913THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
914
915* * *
916
917The class contains the UTF-8 Decoder from Bjoern Hoehrmann which is licensed under the [MIT License](http://opensource.org/licenses/MIT) (see above). Copyright &copy; 2008-2009 [Björn Hoehrmann](http://bjoern.hoehrmann.de/) <bjoern@hoehrmann.de>
918
919The class contains a slightly modified version of the Grisu2 algorithm from Florian Loitsch which is licensed under the [MIT License](http://opensource.org/licenses/MIT) (see above). Copyright &copy; 2009 [Florian Loitsch](http://florian.loitsch.com/)
920
921## Contact
922
923If you have questions regarding the library, I would like to invite you to [open an issue at GitHub](https://github.com/nlohmann/json/issues/new). Please describe your request, problem, or question as detailed as possible, and also mention the version of the library you are using as well as the version of your compiler and operating system. Opening an issue at GitHub allows other users and contributors to this library to collaborate. For instance, I have little experience with MSVC, and most issues in this regard have been solved by a growing community. If you have a look at the [closed issues](https://github.com/nlohmann/json/issues?q=is%3Aissue+is%3Aclosed), you will see that we react quite timely in most cases.
924
925Only if your request would contain confidential information, please [send me an email](mailto:mail@nlohmann.me). For encrypted messages, please use [this key](https://keybase.io/nlohmann/pgp_keys.asc).
926
927## Security
928
929[Commits by Niels Lohmann](https://github.com/nlohmann/json/commits) and [releases](https://github.com/nlohmann/json/releases) are signed with this [PGP Key](https://keybase.io/nlohmann/pgp_keys.asc?fingerprint=797167ae41c0a6d9232e48457f3cea63ae251b69).
930
931## Thanks
932
933I deeply appreciate the help of the following people.
934
935![Contributors](https://raw.githubusercontent.com/nlohmann/json/develop/doc/avatars.png)
936
937- [Teemperor](https://github.com/Teemperor) implemented CMake support and lcov integration, realized escape and Unicode handling in the string parser, and fixed the JSON serialization.
938- [elliotgoodrich](https://github.com/elliotgoodrich) fixed an issue with double deletion in the iterator classes.
939- [kirkshoop](https://github.com/kirkshoop) made the iterators of the class composable to other libraries.
940- [wancw](https://github.com/wanwc) fixed a bug that hindered the class to compile with Clang.
941- Tomas Åblad found a bug in the iterator implementation.
942- [Joshua C. Randall](https://github.com/jrandall) fixed a bug in the floating-point serialization.
943- [Aaron Burghardt](https://github.com/aburgh) implemented code to parse streams incrementally. Furthermore, he greatly improved the parser class by allowing the definition of a filter function to discard undesired elements while parsing.
944- [Daniel Kopeček](https://github.com/dkopecek) fixed a bug in the compilation with GCC 5.0.
945- [Florian Weber](https://github.com/Florianjw) fixed a bug in and improved the performance of the comparison operators.
946- [Eric Cornelius](https://github.com/EricMCornelius) pointed out a bug in the handling with NaN and infinity values. He also improved the performance of the string escaping.
947- [易思龙](https://github.com/likebeta) implemented a conversion from anonymous enums.
948- [kepkin](https://github.com/kepkin) patiently pushed forward the support for Microsoft Visual studio.
949- [gregmarr](https://github.com/gregmarr) simplified the implementation of reverse iterators and helped with numerous hints and improvements. In particular, he pushed forward the implementation of user-defined types.
950- [Caio Luppi](https://github.com/caiovlp) fixed a bug in the Unicode handling.
951- [dariomt](https://github.com/dariomt) fixed some typos in the examples.
952- [Daniel Frey](https://github.com/d-frey) cleaned up some pointers and implemented exception-safe memory allocation.
953- [Colin Hirsch](https://github.com/ColinH) took care of a small namespace issue.
954- [Huu Nguyen](https://github.com/whoshuu) correct a variable name in the documentation.
955- [Silverweed](https://github.com/silverweed) overloaded `parse()` to accept an rvalue reference.
956- [dariomt](https://github.com/dariomt) fixed a subtlety in MSVC type support and implemented the `get_ref()` function to get a reference to stored values.
957- [ZahlGraf](https://github.com/ZahlGraf) added a workaround that allows compilation using Android NDK.
958- [whackashoe](https://github.com/whackashoe) replaced a function that was marked as unsafe by Visual Studio.
959- [406345](https://github.com/406345) fixed two small warnings.
960- [Glen Fernandes](https://github.com/glenfe) noted a potential portability problem in the `has_mapped_type` function.
961- [Corbin Hughes](https://github.com/nibroc) fixed some typos in the contribution guidelines.
962- [twelsby](https://github.com/twelsby) fixed the array subscript operator, an issue that failed the MSVC build, and floating-point parsing/dumping. He further added support for unsigned integer numbers and implemented better roundtrip support for parsed numbers.
963- [Volker Diels-Grabsch](https://github.com/vog) fixed a link in the README file.
964- [msm-](https://github.com/msm-) added support for American Fuzzy Lop.
965- [Annihil](https://github.com/Annihil) fixed an example in the README file.
966- [Themercee](https://github.com/Themercee) noted a wrong URL in the README file.
967- [Lv Zheng](https://github.com/lv-zheng) fixed a namespace issue with `int64_t` and `uint64_t`.
968- [abc100m](https://github.com/abc100m) analyzed the issues with GCC 4.8 and proposed a [partial solution](https://github.com/nlohmann/json/pull/212).
969- [zewt](https://github.com/zewt) added useful notes to the README file about Android.
970- [Róbert Márki](https://github.com/robertmrk) added a fix to use move iterators and improved the integration via CMake.
971- [Chris Kitching](https://github.com/ChrisKitching) cleaned up the CMake files.
972- [Tom Needham](https://github.com/06needhamt) fixed a subtle bug with MSVC 2015 which was also proposed by [Michael K.](https://github.com/Epidal).
973- [Mário Feroldi](https://github.com/thelostt) fixed a small typo.
974- [duncanwerner](https://github.com/duncanwerner) found a really embarrassing performance regression in the 2.0.0 release.
975- [Damien](https://github.com/dtoma) fixed one of the last conversion warnings.
976- [Thomas Braun](https://github.com/t-b) fixed a warning in a test case.
977- [Théo DELRIEU](https://github.com/theodelrieu) patiently and constructively oversaw the long way toward [iterator-range parsing](https://github.com/nlohmann/json/issues/290). He also implemented the magic behind the serialization/deserialization of user-defined types and split the single header file into smaller chunks.
978- [Stefan](https://github.com/5tefan) fixed a minor issue in the documentation.
979- [Vasil Dimov](https://github.com/vasild) fixed the documentation regarding conversions from `std::multiset`.
980- [ChristophJud](https://github.com/ChristophJud) overworked the CMake files to ease project inclusion.
981- [Vladimir Petrigo](https://github.com/vpetrigo) made a SFINAE hack more readable and added Visual Studio 17 to the build matrix.
982- [Denis Andrejew](https://github.com/seeekr) fixed a grammar issue in the README file.
983- [Pierre-Antoine Lacaze](https://github.com/palacaze) found a subtle bug in the `dump()` function.
984- [TurpentineDistillery](https://github.com/TurpentineDistillery) pointed to [`std::locale::classic()`](https://en.cppreference.com/w/cpp/locale/locale/classic) to avoid too much locale joggling, found some nice performance improvements in the parser, improved the benchmarking code, and realized locale-independent number parsing and printing.
985- [cgzones](https://github.com/cgzones) had an idea how to fix the Coverity scan.
986- [Jared Grubb](https://github.com/jaredgrubb) silenced a nasty documentation warning.
987- [Yixin Zhang](https://github.com/qwename) fixed an integer overflow check.
988- [Bosswestfalen](https://github.com/Bosswestfalen) merged two iterator classes into a smaller one.
989- [Daniel599](https://github.com/Daniel599) helped to get Travis execute the tests with Clang's sanitizers.
990- [Jonathan Lee](https://github.com/vjon) fixed an example in the README file.
991- [gnzlbg](https://github.com/gnzlbg) supported the implementation of user-defined types.
992- [Alexej Harm](https://github.com/qis) helped to get the user-defined types working with Visual Studio.
993- [Jared Grubb](https://github.com/jaredgrubb) supported the implementation of user-defined types.
994- [EnricoBilla](https://github.com/EnricoBilla) noted a typo in an example.
995- [Martin Hořeňovský](https://github.com/horenmar) found a way for a 2x speedup for the compilation time of the test suite.
996- [ukhegg](https://github.com/ukhegg) found proposed an improvement for the examples section.
997- [rswanson-ihi](https://github.com/rswanson-ihi) noted a typo in the README.
998- [Mihai Stan](https://github.com/stanmihai4) fixed a bug in the comparison with `nullptr`s.
999- [Tushar Maheshwari](https://github.com/tusharpm) added [cotire](https://github.com/sakra/cotire) support to speed up the compilation.
1000- [TedLyngmo](https://github.com/TedLyngmo) noted a typo in the README, removed unnecessary bit arithmetic, and fixed some `-Weffc++` warnings.
1001- [Krzysztof Woś](https://github.com/krzysztofwos) made exceptions more visible.
1002- [ftillier](https://github.com/ftillier) fixed a compiler warning.
1003- [tinloaf](https://github.com/tinloaf) made sure all pushed warnings are properly popped.
1004- [Fytch](https://github.com/Fytch) found a bug in the documentation.
1005- [Jay Sistar](https://github.com/Type1J) implemented a Meson build description.
1006- [Henry Lee](https://github.com/HenryRLee) fixed a warning in ICC and improved the iterator implementation.
1007- [Vincent Thiery](https://github.com/vthiery) maintains a package for the Conan package manager.
1008- [Steffen](https://github.com/koemeet) fixed a potential issue with MSVC and `std::min`.
1009- [Mike Tzou](https://github.com/Chocobo1) fixed some typos.
1010- [amrcode](https://github.com/amrcode) noted a misleading documentation about comparison of floats.
1011- [Oleg Endo](https://github.com/olegendo) reduced the memory consumption by replacing `<iostream>` with `<iosfwd>`.
1012- [dan-42](https://github.com/dan-42) cleaned up the CMake files to simplify including/reusing of the library.
1013- [Nikita Ofitserov](https://github.com/himikof) allowed for moving values from initializer lists.
1014- [Greg Hurrell](https://github.com/wincent) fixed a typo.
1015- [Dmitry Kukovinets](https://github.com/DmitryKuk) fixed a typo.
1016- [kbthomp1](https://github.com/kbthomp1) fixed an issue related to the Intel OSX compiler.
1017- [Markus Werle](https://github.com/daixtrose) fixed a typo.
1018- [WebProdPP](https://github.com/WebProdPP) fixed a subtle error in a precondition check.
1019- [Alex](https://github.com/leha-bot) noted an error in a code sample.
1020- [Tom de Geus](https://github.com/tdegeus) reported some warnings with ICC and helped fixing them.
1021- [Perry Kundert](https://github.com/pjkundert) simplified reading from input streams.
1022- [Sonu Lohani](https://github.com/sonulohani) fixed a small compilation error.
1023- [Jamie Seward](https://github.com/jseward) fixed all MSVC warnings.
1024- [Nate Vargas](https://github.com/eld00d) added a Doxygen tag file.
1025- [pvleuven](https://github.com/pvleuven) helped fixing a warning in ICC.
1026- [Pavel](https://github.com/crea7or) helped fixing some warnings in MSVC.
1027- [Jamie Seward](https://github.com/jseward) avoided unnecessary string copies in `find()` and `count()`.
1028- [Mitja](https://github.com/Itja) fixed some typos.
1029- [Jorrit Wronski](https://github.com/jowr) updated the Hunter package links.
1030- [Matthias Möller](https://github.com/TinyTinni) added a `.natvis` for the MSVC debug view.
1031- [bogemic](https://github.com/bogemic) fixed some C++17 deprecation warnings.
1032- [Eren Okka](https://github.com/erengy) fixed some MSVC warnings.
1033- [abolz](https://github.com/abolz) integrated the Grisu2 algorithm for proper floating-point formatting, allowing more roundtrip checks to succeed.
1034- [Vadim Evard](https://github.com/Pipeliner) fixed a Markdown issue in the README.
1035- [zerodefect](https://github.com/zerodefect) fixed a compiler warning.
1036- [Kert](https://github.com/kaidokert) allowed to template the string type in the serialization and added the possibility to override the exceptional behavior.
1037- [mark-99](https://github.com/mark-99) helped fixing an ICC error.
1038- [Patrik Huber](https://github.com/patrikhuber) fixed links in the README file.
1039- [johnfb](https://github.com/johnfb) found a bug in the implementation of CBOR's indefinite length strings.
1040- [Paul Fultz II](https://github.com/pfultz2) added a note on the cget package manager.
1041- [Wilson Lin](https://github.com/wla80) made the integration section of the README more concise.
1042- [RalfBielig](https://github.com/ralfbielig) detected and fixed a memory leak in the parser callback.
1043- [agrianius](https://github.com/agrianius) allowed to dump JSON to an alternative string type.
1044- [Kevin Tonon](https://github.com/ktonon) overworked the C++11 compiler checks in CMake.
1045- [Axel Huebl](https://github.com/ax3l) simplified a CMake check and added support for the [Spack package manager](https://spack.io).
1046- [Carlos O'Ryan](https://github.com/coryan) fixed a typo.
1047- [James Upjohn](https://github.com/jammehcow) fixed a version number in the compilers section.
1048- [Chuck Atkins](https://github.com/chuckatkins) adjusted the CMake files to the CMake packaging guidelines
1049- [Jan Schöppach](https://github.com/dns13) fixed a typo.
1050- [martin-mfg](https://github.com/martin-mfg) fixed a typo.
1051- [Matthias Möller](https://github.com/TinyTinni) removed the dependency from `std::stringstream`.
1052- [agrianius](https://github.com/agrianius) added code to use alternative string implementations.
1053- [Daniel599](https://github.com/Daniel599) allowed to use more algorithms with the `items()` function.
1054- [Julius Rakow](https://github.com/jrakow) fixed the Meson include directory and fixed the links to [cppreference.com](cppreference.com).
1055- [Sonu Lohani](https://github.com/sonulohani) fixed the compilation with MSVC 2015 in debug mode.
1056- [grembo](https://github.com/grembo) fixed the test suite and re-enabled several test cases.
1057- [Hyeon Kim](https://github.com/simnalamburt) introduced the macro `JSON_INTERNAL_CATCH` to control the exception handling inside the library.
1058- [thyu](https://github.com/thyu) fixed a compiler warning.
1059
1060Thanks a lot for helping out! Please [let me know](mailto:mail@nlohmann.me) if I forgot someone.
1061
1062
1063## Used third-party tools
1064
1065The library itself consists of a single header file licensed under the MIT license. However, it is built, tested, documented, and whatnot using a lot of third-party tools and services. Thanks a lot!
1066
1067- [**amalgamate.py - Amalgamate C source and header files**](https://github.com/edlund/amalgamate) to create a single header file
1068- [**American fuzzy lop**](http://lcamtuf.coredump.cx/afl/) for fuzz testing
1069- [**AppVeyor**](https://www.appveyor.com) for [continuous integration](https://ci.appveyor.com/project/nlohmann/json) on Windows
1070- [**Artistic Style**](http://astyle.sourceforge.net) for automatic source code identation
1071- [**Catch**](https://github.com/philsquared/Catch) for the unit tests
1072- [**Clang**](http://clang.llvm.org) for compilation with code sanitizers
1073- [**Cmake**](https://cmake.org) for build automation
1074- [**Codacity**](https://www.codacy.com) for further [code analysis](https://www.codacy.com/app/nlohmann/json)
1075- [**Coveralls**](https://coveralls.io) to measure [code coverage](https://coveralls.io/github/nlohmann/json)
1076- [**Coverity Scan**](https://scan.coverity.com) for [static analysis](https://scan.coverity.com/projects/nlohmann-json)
1077- [**cppcheck**](http://cppcheck.sourceforge.net) for static analysis
1078- [**Doxygen**](http://www.stack.nl/~dimitri/doxygen/) to generate [documentation](https://nlohmann.github.io/json/)
1079- [**git-update-ghpages**](https://github.com/rstacruz/git-update-ghpages) to upload the documentation to gh-pages
1080- [**GitHub Changelog Generator**](https://github.com/skywinder/github-changelog-generator) to generate the [ChangeLog](https://github.com/nlohmann/json/blob/develop/ChangeLog.md)
1081- [**Google Benchmark**](https://github.com/google/benchmark) to implement the benchmarks
1082- [**libFuzzer**](http://llvm.org/docs/LibFuzzer.html) to implement fuzz testing for OSS-Fuzz
1083- [**OSS-Fuzz**](https://github.com/google/oss-fuzz) for continuous fuzz testing of the library ([project repository](https://github.com/google/oss-fuzz/tree/master/projects/json))
1084- [**Probot**](https://probot.github.io) for automating maintainer tasks such as closing stale issues, requesting missing information, or detecting toxic comments.
1085- [**send_to_wandbox**](https://github.com/nlohmann/json/blob/develop/doc/scripts/send_to_wandbox.py) to send code examples to [Wandbox](http://melpon.org/wandbox)
1086- [**Travis**](https://travis-ci.org) for [continuous integration](https://travis-ci.org/nlohmann/json) on Linux and macOS
1087- [**Valgrind**](http://valgrind.org) to check for correct memory management
1088- [**Wandbox**](http://melpon.org/wandbox) for [online examples](https://wandbox.org/permlink/TarF5pPn9NtHQjhf)
1089
1090
1091## Projects using JSON for Modern C++
1092
1093The library is currently used in Apple macOS Sierra and iOS 10. I am not sure what they are using the library for, but I am happy that it runs on so many devices.
1094
1095
1096## Notes
1097
1098- The code contains numerous debug **assertions** which can be switched off by defining the preprocessor macro `NDEBUG`, see the [documentation of `assert`](https://en.cppreference.com/w/cpp/error/assert). In particular, note [`operator[]`](https://nlohmann.github.io/json/classnlohmann_1_1basic__json_a2e26bd0b0168abb61f67ad5bcd5b9fa1.html#a2e26bd0b0168abb61f67ad5bcd5b9fa1) implements **unchecked access** for const objects: If the given key is not present, the behavior is undefined (think of a dereferenced null pointer) and yields an [assertion failure](https://github.com/nlohmann/json/issues/289) if assertions are switched on. If you are not sure whether an element in an object exists, use checked access with the [`at()` function](https://nlohmann.github.io/json/classnlohmann_1_1basic__json_a674de1ee73e6bf4843fc5dc1351fb726.html#a674de1ee73e6bf4843fc5dc1351fb726).
1099- As the exact type of a number is not defined in the [JSON specification](http://rfc7159.net/rfc7159), this library tries to choose the best fitting C++ number type automatically. As a result, the type `double` may be used to store numbers which may yield [**floating-point exceptions**](https://github.com/nlohmann/json/issues/181) in certain rare situations if floating-point exceptions have been unmasked in the calling code. These exceptions are not caused by the library and need to be fixed in the calling code, such as by re-masking the exceptions prior to calling library functions.
1100- The library supports **Unicode input** as follows:
1101  - Only **UTF-8** encoded input is supported which is the default encoding for JSON according to [RFC 7159](http://rfc7159.net/rfc7159#rfc.section.8.1).
1102  - Other encodings such as Latin-1, UTF-16, or UTF-32 are not supported and will yield parse or serialization errors.
1103  - [Unicode noncharacters](http://www.unicode.org/faq/private_use.html#nonchar1) will not be replaced by the library.
1104  - Invalid surrogates (e.g., incomplete pairs such as `\uDEAD`) will yield parse errors.
1105  - The strings stored in the library are UTF-8 encoded. When using the default string type (`std::string`), note that its length/size functions return the number of stored bytes rather than the number of characters or glyphs.
1106- The code can be compiled without C++ **runtime type identification** features; that is, you can use the `-fno-rtti` compiler flag.
1107- **Exceptions** are used widely within the library. They can, however, be switched off with either using the compiler flag `-fno-exceptions` or by defining the symbol `JSON_NOEXCEPTION`. In this case, exceptions are replaced by an `abort()` call.
1108- By default, the library does not preserve the **insertion order of object elements**. This is standards-compliant, as the [JSON standard](https://tools.ietf.org/html/rfc7159.html) defines objects as "an unordered collection of zero or more name/value pairs". If you do want to preserve the insertion order, you can specialize the object type with containers like [`tsl::ordered_map`](https://github.com/Tessil/ordered-map) ([integration](https://github.com/nlohmann/json/issues/546#issuecomment-304447518)) or [`nlohmann::fifo_map`](https://github.com/nlohmann/fifo_map) ([integration](https://github.com/nlohmann/json/issues/485#issuecomment-333652309)).
1109
1110
1111## Execute unit tests
1112
1113To compile and run the tests, you need to execute
1114
1115```sh
1116$ mkdir build
1117$ cd build
1118$ cmake ..
1119$ cmake --build .
1120$ ctest --output-on-failure
1121```
1122
1123For more information, have a look at the file [.travis.yml](https://github.com/nlohmann/json/blob/master/.travis.yml).
1124