Call the freeCB function a manual timer stop call
[src/libafb-helpers.git] / json.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)](http://melpon.org/wandbox/permlink/nv9fOg0XVVhWmFFy)
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   - [Implicit conversions](#implicit-conversions)
25   - [Conversions to/from arbitrary types](#arbitrary-types-conversions)
26   - [Binary formats (CBOR and MessagePack)](#binary-formats-cbor-and-messagepack)
27 - [Supported compilers](#supported-compilers)
28 - [License](#license)
29 - [Thanks](#thanks)
30 - [Used third-party tools](#used-third-party-tools)
31 - [Projects using JSON for Modern C++](#projects-using-json-for-modern-c)
32 - [Notes](#notes)
33 - [Execute unit tests](#execute-unit-tests)
34
35 ## Design goals
36
37 There 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:
38
39 - **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.
40
41 - **Trivial integration**. Our whole code consists of a single header file [`json.hpp`](https://github.com/nlohmann/json/blob/develop/src/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.
42
43 - **Serious testing**. Our class is heavily [unit-tested](https://github.com/nlohmann/json/blob/master/test/src/unit.cpp) and covers [100%](https://coveralls.io/r/nlohmann/json) of the code, including all exceptional behavior. Furthermore, we checked with [Valgrind](http://valgrind.org) that there are no memory leaks. To maintain high quality, the project is following the [Core Infrastructure Initiative (CII) best practices](https://bestpractices.coreinfrastructure.org/projects/289).
44
45 Other aspects were not so important to us:
46
47 - **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.
48
49 - **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.
50
51 See the [contribution guidelines](https://github.com/nlohmann/json/blob/master/.github/CONTRIBUTING.md#please-dont) for more information.
52
53
54 ## Integration
55
56 The single required source, file `json.hpp` is in the `src` directory or [released here](https://github.com/nlohmann/json/releases). All you need to do is add
57
58 ```cpp
59 #include "json.hpp"
60
61 // for convenience
62 using json = nlohmann::json;
63 ```
64
65 to the files you want to use JSON objects. That's it. Do not forget to set the necessary switches to enable C++11 (e.g., `-std=c++11` for GCC and Clang).
66
67 :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`.
68
69 If you are using the [Meson Build System](http://mesonbuild.com), then you can wrap this repo as a subproject.
70
71 If 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.
72
73 If you are using [hunter](https://github.com/ruslo/hunter/) on your project for external dependencies, then you can use the [nlohman_json package](https://github.com/ruslo/hunter/wiki/pkg.nlohmann_json). Please see the hunter project for any issues regarding the packaging.
74
75 :warning: [Version 3.0.0](https://github.com/nlohmann/json/wiki/Road-toward-3.0.0) is currently under development. Branch `develop` is used for the ongoing work and is probably **unstable**. Please use the `master` branch for the last stable version 2.1.1.
76
77
78 ## Examples
79
80 Beside 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_a602f275f0359ab181221384989810604.html#a602f275f0359ab181221384989810604)). 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)).
81
82 ### JSON as first-class data type
83
84 Here are some examples to give you an idea how to use the class.
85
86 Assume you want to create the JSON object
87
88 ```json
89 {
90   "pi": 3.141,
91   "happy": true,
92   "name": "Niels",
93   "nothing": null,
94   "answer": {
95     "everything": 42
96   },
97   "list": [1, 0, 2],
98   "object": {
99     "currency": "USD",
100     "value": 42.99
101   }
102 }
103 ```
104
105 With the JSON class, you could write:
106
107 ```cpp
108 // create an empty structure (null)
109 json j;
110
111 // add a number that is stored as double (note the implicit conversion of j to an object)
112 j["pi"] = 3.141;
113
114 // add a Boolean that is stored as bool
115 j["happy"] = true;
116
117 // add a string that is stored as std::string
118 j["name"] = "Niels";
119
120 // add another null object by passing nullptr
121 j["nothing"] = nullptr;
122
123 // add an object inside the object
124 j["answer"]["everything"] = 42;
125
126 // add an array that is stored as std::vector (using an initializer list)
127 j["list"] = { 1, 0, 2 };
128
129 // add another object (using an initializer list of pairs)
130 j["object"] = { {"currency", "USD"}, {"value", 42.99} };
131
132 // instead, you could also write (which looks very similar to the JSON above)
133 json j2 = {
134   {"pi", 3.141},
135   {"happy", true},
136   {"name", "Niels"},
137   {"nothing", nullptr},
138   {"answer", {
139     {"everything", 42}
140   }},
141   {"list", {1, 0, 2}},
142   {"object", {
143     {"currency", "USD"},
144     {"value", 42.99}
145   }}
146 };
147 ```
148
149 Note that in all these cases, you never need to "tell" the compiler which JSON value you want to use. If you want to be explicit or express some edge cases, the functions `json::array` and `json::object` will help:
150
151 ```cpp
152 // a way to express the empty array []
153 json empty_array_explicit = json::array();
154
155 // ways to express the empty object {}
156 json empty_object_implicit = json({});
157 json empty_object_explicit = json::object();
158
159 // a way to express an _array_ of key/value pairs [["currency", "USD"], ["value", 42.99]]
160 json array_not_object = { json::array({"currency", "USD"}), json::array({"value", 42.99}) };
161 ```
162
163
164 ### Serialization / Deserialization
165
166 #### To/from strings
167
168 You can create an object (deserialization) by appending `_json` to a string literal:
169
170 ```cpp
171 // create object from string literal
172 json j = "{ \"happy\": true, \"pi\": 3.141 }"_json;
173
174 // or even nicer with a raw string literal
175 auto j2 = R"(
176   {
177     "happy": true,
178     "pi": 3.141
179   }
180 )"_json;
181 ```
182
183 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.
184
185 The above example can also be expressed explicitly using `json::parse()`:
186
187 ```cpp
188 // parse explicitly
189 auto j3 = json::parse("{ \"happy\": true, \"pi\": 3.141 }");
190 ```
191
192 You can also get a string representation (serialize):
193
194 ```cpp
195 // explicit conversion to string
196 std::string s = j.dump();    // {\"happy\":true,\"pi\":3.141}
197
198 // serialization with pretty printing
199 // pass in the amount of spaces to indent
200 std::cout << j.dump(4) << std::endl;
201 // {
202 //     "happy": true,
203 //     "pi": 3.141
204 // }
205 ```
206
207 #### To/from streams (e.g. files, string streams)
208
209 You can also use streams to serialize and deserialize:
210
211 ```cpp
212 // deserialize from standard input
213 json j;
214 std::cin >> j;
215
216 // serialize to standard output
217 std::cout << j;
218
219 // the setw manipulator was overloaded to set the indentation for pretty printing
220 std::cout << std::setw(4) << j << std::endl;
221 ```
222
223 These operators work for any subclasses of `std::istream` or `std::ostream`. Here is the same example with files:
224
225 ```cpp
226 // read a JSON file
227 std::ifstream i("file.json");
228 json j;
229 i >> j;
230
231 // write prettified JSON to another file
232 std::ofstream o("pretty.json");
233 o << std::setw(4) << j << std::endl;
234 ```
235
236 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.
237
238 #### Read from iterator range
239
240 You can also read 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>`:
241
242 ```cpp
243 std::vector<std::uint8_t> v = {'t', 'r', 'u', 'e'};
244 json j = json::parse(v.begin(), v.end());
245 ```
246
247 You may leave the iterators for the range [begin, end):
248
249 ```cpp
250 std::vector<std::uint8_t> v = {'t', 'r', 'u', 'e'};
251 json j = json::parse(v);
252 ```
253
254
255 ### STL-like access
256
257 We designed the JSON class to behave just like an STL container. In fact, it satisfies the [**ReversibleContainer**](http://en.cppreference.com/w/cpp/concept/ReversibleContainer) requirement.
258
259 ```cpp
260 // create an array using push_back
261 json j;
262 j.push_back("foo");
263 j.push_back(1);
264 j.push_back(true);
265
266 // also use emplace_back
267 j.emplace_back(1.78);
268
269 // iterate the array
270 for (json::iterator it = j.begin(); it != j.end(); ++it) {
271   std::cout << *it << '\n';
272 }
273
274 // range-based for
275 for (auto& element : j) {
276   std::cout << element << '\n';
277 }
278
279 // getter/setter
280 const std::string tmp = j[0];
281 j[1] = 42;
282 bool foo = j.at(2);
283
284 // comparison
285 j == "[\"foo\", 1, true]"_json;  // true
286
287 // other stuff
288 j.size();     // 3 entries
289 j.empty();    // false
290 j.type();     // json::value_t::array
291 j.clear();    // the array is empty again
292
293 // convenience type checkers
294 j.is_null();
295 j.is_boolean();
296 j.is_number();
297 j.is_object();
298 j.is_array();
299 j.is_string();
300
301 // create an object
302 json o;
303 o["foo"] = 23;
304 o["bar"] = false;
305 o["baz"] = 3.141;
306
307 // also use emplace
308 o.emplace("weather", "sunny");
309
310 // special iterator member functions for objects
311 for (json::iterator it = o.begin(); it != o.end(); ++it) {
312   std::cout << it.key() << " : " << it.value() << "\n";
313 }
314
315 // find an entry
316 if (o.find("foo") != o.end()) {
317   // there is an entry with key "foo"
318 }
319
320 // or simpler using count()
321 int foo_present = o.count("foo"); // 1
322 int fob_present = o.count("fob"); // 0
323
324 // delete an entry
325 o.erase("foo");
326 ```
327
328
329 ### Conversion from STL containers
330
331 Any sequence container (`std::array`, `std::vector`, `std::deque`, `std::forward_list`, `std::list`) whose values can be used to construct JSON types (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 how the elements are ordered in the respective STL container.
332
333 ```cpp
334 std::vector<int> c_vector {1, 2, 3, 4};
335 json j_vec(c_vector);
336 // [1, 2, 3, 4]
337
338 std::deque<double> c_deque {1.2, 2.3, 3.4, 5.6};
339 json j_deque(c_deque);
340 // [1.2, 2.3, 3.4, 5.6]
341
342 std::list<bool> c_list {true, true, false, true};
343 json j_list(c_list);
344 // [true, true, false, true]
345
346 std::forward_list<int64_t> c_flist {12345678909876, 23456789098765, 34567890987654, 45678909876543};
347 json j_flist(c_flist);
348 // [12345678909876, 23456789098765, 34567890987654, 45678909876543]
349
350 std::array<unsigned long, 4> c_array {{1, 2, 3, 4}};
351 json j_array(c_array);
352 // [1, 2, 3, 4]
353
354 std::set<std::string> c_set {"one", "two", "three", "four", "one"};
355 json j_set(c_set); // only one entry for "one" is used
356 // ["four", "one", "three", "two"]
357
358 std::unordered_set<std::string> c_uset {"one", "two", "three", "four", "one"};
359 json j_uset(c_uset); // only one entry for "one" is used
360 // maybe ["two", "three", "four", "one"]
361
362 std::multiset<std::string> c_mset {"one", "two", "one", "four"};
363 json j_mset(c_mset); // both entries for "one" are used
364 // maybe ["one", "two", "one", "four"]
365
366 std::unordered_multiset<std::string> c_umset {"one", "two", "one", "four"};
367 json j_umset(c_umset); // both entries for "one" are used
368 // maybe ["one", "two", "one", "four"]
369 ```
370
371 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 types (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.
372
373 ```cpp
374 std::map<std::string, int> c_map { {"one", 1}, {"two", 2}, {"three", 3} };
375 json j_map(c_map);
376 // {"one": 1, "three": 3, "two": 2 }
377
378 std::unordered_map<const char*, double> c_umap { {"one", 1.2}, {"two", 2.3}, {"three", 3.4} };
379 json j_umap(c_umap);
380 // {"one": 1.2, "two": 2.3, "three": 3.4}
381
382 std::multimap<std::string, bool> c_mmap { {"one", true}, {"two", true}, {"three", false}, {"three", true} };
383 json j_mmap(c_mmap); // only one entry for key "three" is used
384 // maybe {"one": true, "two": true, "three": true}
385
386 std::unordered_multimap<std::string, bool> c_ummap { {"one", true}, {"two", true}, {"three", false}, {"three", true} };
387 json j_ummap(c_ummap); // only one entry for key "three" is used
388 // maybe {"one": true, "two": true, "three": true}
389 ```
390
391 ### JSON Pointer and JSON Patch
392
393 The 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.
394
395 ```cpp
396 // a JSON value
397 json j_original = R"({
398   "baz": ["one", "two", "three"],
399   "foo": "bar"
400 })"_json;
401
402 // access members with a JSON pointer (RFC 6901)
403 j_original["/baz/1"_json_pointer];
404 // "two"
405
406 // a JSON patch (RFC 6902)
407 json j_patch = R"([
408   { "op": "replace", "path": "/baz", "value": "boo" },
409   { "op": "add", "path": "/hello", "value": ["world"] },
410   { "op": "remove", "path": "/foo"}
411 ])"_json;
412
413 // apply the patch
414 json j_result = j_original.patch(j_patch);
415 // {
416 //    "baz": "boo",
417 //    "hello": ["world"]
418 // }
419
420 // calculate a JSON patch from two JSON values
421 json::diff(j_result, j_original);
422 // [
423 //   { "op":" replace", "path": "/baz", "value": ["one", "two", "three"] },
424 //   { "op": "remove","path": "/hello" },
425 //   { "op": "add", "path": "/foo", "value": "bar" }
426 // ]
427 ```
428
429
430 ### Implicit conversions
431
432 The type of the JSON object is determined automatically by the expression to store. Likewise, the stored value is implicitly converted.
433
434 ```cpp
435 // strings
436 std::string s1 = "Hello, world!";
437 json js = s1;
438 std::string s2 = js;
439
440 // Booleans
441 bool b1 = true;
442 json jb = b1;
443 bool b2 = jb;
444
445 // numbers
446 int i = 42;
447 json jn = i;
448 double f = jn;
449
450 // etc.
451 ```
452
453 You can also explicitly ask for the value:
454
455 ```cpp
456 std::string vs = js.get<std::string>();
457 bool vb = jb.get<bool>();
458 int vi = jn.get<int>();
459
460 // etc.
461 ```
462
463 ### Arbitrary types conversions
464
465 Every type can be serialized in JSON, not just STL-containers and scalar types. Usually, you would do something along those lines:
466
467 ```cpp
468 namespace ns {
469     // a simple struct to model a person
470     struct person {
471         std::string name;
472         std::string address;
473         int age;
474     };
475 }
476
477 ns::person p = {"Ned Flanders", "744 Evergreen Terrace", 60};
478
479 // convert to JSON: copy each value into the JSON object
480 json j;
481 j["name"] = p.name;
482 j["address"] = p.address;
483 j["age"] = p.age;
484
485 // ...
486
487 // convert from JSON: copy each value from the JSON object
488 ns::person p {
489     j["name"].get<std::string>(),
490     j["address"].get<std::string>(),
491     j["age"].get<int>()
492 };
493 ```
494
495 It works, but that's quite a lot of boilerplate... Fortunately, there's a better way:
496
497 ```cpp
498 // create a person
499 ns::person p {"Ned Flanders", "744 Evergreen Terrace", 60};
500
501 // conversion: person -> json
502 json j = p;
503
504 std::cout << j << std::endl;
505 // {"address":"744 Evergreen Terrace","age":60,"name":"Ned Flanders"}
506
507 // conversion: json -> person
508 ns::person p2 = j;
509
510 // that's it
511 assert(p == p2);
512 ```
513
514 #### Basic usage
515
516 To make this work with one of your types, you only need to provide two functions:
517
518 ```cpp
519 using nlohmann::json;
520
521 namespace ns {
522     void to_json(json& j, const person& p) {
523         j = json{{"name", p.name}, {"address", p.address}, {"age", p.age}};
524     }
525
526     void from_json(const json& j, person& p) {
527         p.name = j.at("name").get<std::string>();
528         p.address = j.at("address").get<std::string>();
529         p.age = j.at("age").get<int>();
530     }
531 } // namespace ns
532 ```
533
534 That's all! When calling the `json` constructor with your type, your custom `to_json` method will be automatically called.
535 Likewise, when calling `get<your_type>()`, the `from_json` method will be called.
536
537 Some important things:
538
539 * 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).
540 * When using `get<your_type>()`, `your_type` **MUST** be [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible). (There is a way to bypass this requirement described later.)
541 * 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 exists, `at` throws an exception that you can handle, whereas `operator[]` exhibits undefined behavior.
542 * 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.
543 * You do not need to add serializers or deserializers for STL types like `std::vector`: the library already implements these.
544
545
546 #### How do I convert third-party types?
547
548 This requires a bit more advanced technique. But first, let's see how this conversion mechanism works:
549
550 The library uses **JSON Serializers** to convert types to json.
551 The default serializer for `nlohmann::json` is `nlohmann::adl_serializer` (ADL means [Argument-Dependent Lookup](http://en.cppreference.com/w/cpp/language/adl)).
552
553 It is implemented like this (simplified):
554
555 ```cpp
556 template <typename T>
557 struct adl_serializer {
558     static void to_json(json& j, const T& value) {
559         // calls the "to_json" method in T's namespace
560     }
561
562     static void from_json(const json& j, T& value) {
563         // same thing, but with the "from_json" method
564     }
565 };
566 ```
567
568 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`...
569
570 To solve this, you need to add a specialization of `adl_serializer` to the `nlohmann` namespace, here's an example:
571
572 ```cpp
573 // partial specialization (full specialization works too)
574 namespace nlohmann {
575     template <typename T>
576     struct adl_serializer<boost::optional<T>> {
577         static void to_json(json& j, const boost::optional<T>& opt) {
578             if (opt == boost::none) {
579                 j = nullptr;
580             } else {
581               j = *opt; // this will call adl_serializer<T>::to_json which will
582                         // find the free function to_json in T's namespace!
583             }
584         }
585
586         static void from_json(const json& j, boost::optional<T>& opt) {
587             if (j.is_null()) {
588                 opt = boost::none;
589             } else {
590                 opt = j.get<T>(); // same as above, but with 
591                                   // adl_serializer<T>::from_json
592             }
593         }
594     };
595 }
596 ```
597
598 #### How can I use `get()` for non-default constructible/non-copyable types?
599
600 There is a way, if your type is [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible). You will need to specialize the `adl_serializer` as well, but with a special `from_json` overload:
601
602 ```cpp
603 struct move_only_type {
604     move_only_type() = delete;
605     move_only_type(int ii): i(ii) {}
606     move_only_type(const move_only_type&) = delete;
607     move_only_type(move_only_type&&) = default;
608     
609     int i;
610 };
611
612 namespace nlohmann {
613     template <>
614     struct adl_serializer<move_only_type> {
615         // note: the return type is no longer 'void', and the method only takes
616         // one argument
617         static move_only_type from_json(const json& j) {
618             return {j.get<int>()};
619         }
620         
621         // Here's the catch! You must provide a to_json method! Otherwise you
622         // will not be able to convert move_only_type to json, since you fully
623         // specialized adl_serializer on that type
624         static void to_json(json& j, move_only_type t) {
625             j = t.i;
626         }
627     };
628 }
629 ```
630
631 #### Can I write my own serializer? (Advanced use)
632
633 Yes. 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.
634
635 If you write your own serializer, you'll need to do a few things:
636
637 * use a different `basic_json` alias than `nlohmann::json` (the last template parameter of `basic_json` is the `JSONSerializer`)
638 * use your `basic_json` alias (or a template parameter) in all your `to_json`/`from_json` methods
639 * use `nlohmann::to_json` and `nlohmann::from_json` when you need ADL
640
641 Here is an example, without simplifications, that only accepts types with a size <= 32, and uses ADL.
642
643 ```cpp
644 // You should use void as a second template argument
645 // if you don't need compile-time checks on T
646 template<typename T, typename SFINAE = typename std::enable_if<sizeof(T) <= 32>::type>
647 struct less_than_32_serializer {
648     template <typename BasicJsonType>
649     static void to_json(BasicJsonType& j, T value) {
650         // we want to use ADL, and call the correct to_json overload
651         using nlohmann::to_json; // this method is called by adl_serializer,
652                                  // this is where the magic happens
653         to_json(j, value);
654     }
655     
656     template <typename BasicJsonType>
657     static void from_json(const BasicJsonType& j, T& value) {
658         // same thing here
659         using nlohmann::from_json;
660         from_json(j, value);
661     }
662 };
663 ```
664
665 Be **very** careful when reimplementing your serializer, you can stack overflow if you don't pay attention:
666
667 ```cpp
668 template <typename T, void>
669 struct bad_serializer
670 {
671     template <typename BasicJsonType>
672     static void to_json(BasicJsonType& j, const T& value) {
673       // this calls BasicJsonType::json_serializer<T>::to_json(j, value);
674       // if BasicJsonType::json_serializer == bad_serializer ... oops!
675       j = value;
676     }
677     
678     template <typename BasicJsonType>
679     static void to_json(const BasicJsonType& j, T& value) {
680       // this calls BasicJsonType::json_serializer<T>::from_json(j, value);
681       // if BasicJsonType::json_serializer == bad_serializer ... oops!
682       value = j.template get<T>(); // oops!
683     }
684 };
685 ```
686
687 ### Binary formats (CBOR and MessagePack)
688
689 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 [CBOR](http://cbor.io) (Concise Binary Object Representation) and [MessagePack](http://msgpack.org) to efficiently encode JSON values to byte vectors and to decode such vectors.
690
691 ```cpp
692 // create a JSON value
693 json j = R"({"compact": true, "schema": 0})"_json;
694
695 // serialize to CBOR
696 std::vector<std::uint8_t> v_cbor = json::to_cbor(j);
697
698 // 0xa2, 0x67, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x63, 0x74, 0xf5, 0x66, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x00
699
700 // roundtrip
701 json j_from_cbor = json::from_cbor(v_cbor);
702
703 // serialize to MessagePack
704 std::vector<std::uint8_t> v_msgpack = json::to_msgpack(j);
705
706 // 0x82, 0xa7, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x63, 0x74, 0xc3, 0xa6, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x00
707
708 // roundtrip
709 json j_from_msgpack = json::from_msgpack(v_msgpack);
710 ```
711
712
713 ## Supported compilers
714
715 Though it's 2016 already, the support for C++11 is still a bit sparse. Currently, the following compilers are known to work:
716
717 - GCC 4.9 - 7.1 (and possibly later)
718 - Clang 3.4 - 5.0 (and possibly later)
719 - Microsoft Visual C++ 2015 / Build Tools 14.0.25123.0 (and possibly later)
720 - Microsoft Visual C++ 2017 / Build Tools 15.1.548.43366 (and possibly later)
721
722 I would be happy to learn about other compilers/versions.
723
724 Please note:
725
726 - 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.
727 - 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.
728  
729     ```
730     APP_STL := c++_shared
731     NDK_TOOLCHAIN_VERSION := clang3.6
732     APP_CPPFLAGS += -frtti -fexceptions
733     ```
734  
735     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.
736
737 - 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).
738
739 The 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):
740
741 | Compiler        | Operating System             | Version String |
742 |-----------------|------------------------------|----------------|
743 | GCC 4.9.4       | Ubuntu 14.04.5 LTS           | g++-4.9 (Ubuntu 4.9.4-2ubuntu1~14.04.1) 4.9.4 |
744 | GCC 5.4.1       | Ubuntu 14.04.5 LTS           | g++-5 (Ubuntu 5.4.1-2ubuntu1~14.04) 5.4.1 20160904 |
745 | GCC 6.3.0       | Ubuntu 14.04.5 LTS           | g++-6 (Ubuntu/Linaro 6.3.0-18ubuntu2~14.04) 6.3.0 20170519 |
746 | GCC 7.1.0       | Ubuntu 14.04.5 LTS           | g++-7 (Ubuntu 7.1.0-5ubuntu2~14.04) 7.1.0
747 | Clang 3.5.0     | Ubuntu 14.04.5 LTS           | clang version 3.5.0-4ubuntu2~trusty2 (tags/RELEASE_350/final) |
748 | Clang 3.6.2     | Ubuntu 14.04.5 LTS           | clang version 3.6.2-svn240577-1~exp1 (branches/release_36) |
749 | Clang 3.7.1     | Ubuntu 14.04.5 LTS           | clang version 3.7.1-svn253571-1~exp1 (branches/release_37) |
750 | Clang 3.8.0     | Ubuntu 14.04.5 LTS           | clang version 3.8.0-2ubuntu3~trusty5 (tags/RELEASE_380/final) |
751 | Clang 3.9.1     | Ubuntu 14.04.5 LTS           | clang version 3.9.1-4ubuntu3~14.04.2 (tags/RELEASE_391/rc2) |
752 | Clang 4.0.1     | Ubuntu 14.04.5 LTS           | clang version 4.0.1-svn305264-1~exp1 (branches/release_40) |
753 | Clang 5.0.0     | Ubuntu 14.04.5 LTS           | clang version 5.0.0-svn310902-1~exp1 (branches/release_50) |
754 | Clang Xcode 6.4 | Darwin Kernel Version 14.3.0 (OSX 10.10.3) | Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn) |
755 | Clang Xcode 7.3 | Darwin Kernel Version 15.0.0 (OSX 10.10.5) | Apple LLVM version 7.3.0 (clang-703.0.29) |
756 | Clang Xcode 8.0 | Darwin Kernel Version 15.6.0 | Apple LLVM version 8.0.0 (clang-800.0.38) |
757 | Clang Xcode 8.1 | Darwin Kernel Version 16.1.0 (macOS 10.12.1) | Apple LLVM version 8.0.0 (clang-800.0.42.1) |
758 | Clang Xcode 8.2 | Darwin Kernel Version 16.1.0 (macOS 10.12.1) | Apple LLVM version 8.0.0 (clang-800.0.42.1) |
759 | Clang Xcode 8.3 | Darwin Kernel Version 16.5.0 (macOS 10.12.4) | Apple LLVM version 8.1.0 (clang-802.0.38) |
760 | Clang Xcode 9 beta | Darwin Kernel Version 16.6.0 (macOS 10.12.5) | Apple LLVM version 9.0.0 (clang-900.0.26) |
761 | Visual Studio 14 2015 | Windows Server 2012 R2 (x64) | Microsoft (R) Build Engine version 14.0.25420.1 | 
762 | Visual Studio 2017 | Windows Server 2016 | Microsoft (R) Build Engine version 15.1.1012.6693 |
763
764 ## License
765
766 <img align="right" src="http://opensource.org/trademarks/opensource/OSI-Approved-License-100x137.png">
767
768 The class is licensed under the [MIT License](http://opensource.org/licenses/MIT):
769
770 Copyright &copy; 2013-2017 [Niels Lohmann](http://nlohmann.me)
771
772 Permission 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:
773
774 The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
775
776 THE 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.
777
778
779 ## Thanks
780
781 I deeply appreciate the help of the following people.
782
783 - [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.
784 - [elliotgoodrich](https://github.com/elliotgoodrich) fixed an issue with double deletion in the iterator classes.
785 - [kirkshoop](https://github.com/kirkshoop) made the iterators of the class composable to other libraries.
786 - [wancw](https://github.com/wanwc) fixed a bug that hindered the class to compile with Clang.
787 - Tomas Åblad found a bug in the iterator implementation.
788 - [Joshua C. Randall](https://github.com/jrandall) fixed a bug in the floating-point serialization.
789 - [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.
790 - [Daniel Kopeček](https://github.com/dkopecek) fixed a bug in the compilation with GCC 5.0.
791 - [Florian Weber](https://github.com/Florianjw) fixed a bug in and improved the performance of the comparison operators.
792 - [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.
793 - [易思龙](https://github.com/likebeta) implemented a conversion from anonymous enums.
794 - [kepkin](https://github.com/kepkin) patiently pushed forward the support for Microsoft Visual studio.
795 - [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.
796 - [Caio Luppi](https://github.com/caiovlp) fixed a bug in the Unicode handling.
797 - [dariomt](https://github.com/dariomt) fixed some typos in the examples.
798 - [Daniel Frey](https://github.com/d-frey) cleaned up some pointers and implemented exception-safe memory allocation.
799 - [Colin Hirsch](https://github.com/ColinH) took care of a small namespace issue.
800 - [Huu Nguyen](https://github.com/whoshuu) correct a variable name in the documentation.
801 - [Silverweed](https://github.com/silverweed) overloaded `parse()` to accept an rvalue reference.
802 - [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.
803 - [ZahlGraf](https://github.com/ZahlGraf) added a workaround that allows compilation using Android NDK.
804 - [whackashoe](https://github.com/whackashoe) replaced a function that was marked as unsafe by Visual Studio.
805 - [406345](https://github.com/406345) fixed two small warnings.
806 - [Glen Fernandes](https://github.com/glenfe) noted a potential portability problem in the `has_mapped_type` function.
807 - [Corbin Hughes](https://github.com/nibroc) fixed some typos in the contribution guidelines.
808 - [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.
809 - [Volker Diels-Grabsch](https://github.com/vog) fixed a link in the README file.
810 - [msm-](https://github.com/msm-) added support for american fuzzy lop. 
811 - [Annihil](https://github.com/Annihil) fixed an example in the README file.
812 - [Themercee](https://github.com/Themercee) noted a wrong URL in the README file.
813 - [Lv Zheng](https://github.com/lv-zheng) fixed a namespace issue with `int64_t` and `uint64_t`.
814 - [abc100m](https://github.com/abc100m) analyzed the issues with GCC 4.8 and proposed a [partial solution](https://github.com/nlohmann/json/pull/212).
815 - [zewt](https://github.com/zewt) added useful notes to the README file about Android.
816 - [Róbert Márki](https://github.com/robertmrk) added a fix to use move iterators and improved the integration via CMake.
817 - [Chris Kitching](https://github.com/ChrisKitching) cleaned up the CMake files.
818 - [Tom Needham](https://github.com/06needhamt) fixed a subtle bug with MSVC 2015 which was also proposed by [Michael K.](https://github.com/Epidal).
819 - [Mário Feroldi](https://github.com/thelostt) fixed a small typo.
820 - [duncanwerner](https://github.com/duncanwerner) found a really embarrassing performance regression in the 2.0.0 release.
821 - [Damien](https://github.com/dtoma) fixed one of the last conversion warnings.
822 - [Thomas Braun](https://github.com/t-b) fixed a warning in a test case.
823 - [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.
824 - [Stefan](https://github.com/5tefan) fixed a minor issue in the documentation.
825 - [Vasil Dimov](https://github.com/vasild) fixed the documentation regarding conversions from `std::multiset`.
826 - [ChristophJud](https://github.com/ChristophJud) overworked the CMake files to ease project inclusion.
827 - [Vladimir Petrigo](https://github.com/vpetrigo) made a SFINAE hack more readable and added Visual Studio 17 to the build matrix.
828 - [Denis Andrejew](https://github.com/seeekr) fixed a grammar issue in the README file.
829 - [Pierre-Antoine Lacaze](https://github.com/palacaze) found a subtle bug in the `dump()` function.
830 - [TurpentineDistillery](https://github.com/TurpentineDistillery) pointed to [`std::locale::classic()`](http://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.
831 - [cgzones](https://github.com/cgzones) had an idea how to fix the Coverity scan.
832 - [Jared Grubb](https://github.com/jaredgrubb) silenced a nasty documentation warning.
833 - [Yixin Zhang](https://github.com/qwename) fixed an integer overflow check.
834 - [Bosswestfalen](https://github.com/Bosswestfalen) merged two iterator classes into a smaller one.
835 - [Daniel599](https://github.com/Daniel599) helped to get Travis execute the tests with Clang's sanitizers.
836 - [Jonathan Lee](https://github.com/vjon) fixed an example in the README file.
837 - [gnzlbg](https://github.com/gnzlbg) supported the implementation of user-defined types.
838 - [Alexej Harm](https://github.com/qis) helped to get the user-defined types working with Visual Studio.
839 - [Jared Grubb](https://github.com/jaredgrubb) supported the implementation of user-defined types.
840 - [EnricoBilla](https://github.com/EnricoBilla) noted a typo in an example.
841 - [Martin Hořeňovský](https://github.com/horenmar) found a way for a 2x speedup for the compilation time of the test suite.
842 - [ukhegg](https://github.com/ukhegg) found proposed an improvement for the examples section.
843 - [rswanson-ihi](https://github.com/rswanson-ihi) noted a typo in the README.
844 - [Mihai Stan](https://github.com/stanmihai4) fixed a bug in the comparison with `nullptr`s.
845 - [Tushar Maheshwari](https://github.com/tusharpm) added [cotire](https://github.com/sakra/cotire) support to speed up the compilation.
846 - [TedLyngmo](https://github.com/TedLyngmo) noted a typo in the README, removed unnecessary bit arithmetic, and fixed some `-Weffc++` warnings.
847 - [Krzysztof Woś](https://github.com/krzysztofwos) made exceptions more visible.
848 - [ftillier](https://github.com/ftillier) fixed a compiler warning.
849 - [tinloaf](https://github.com/tinloaf) made sure all pushed warnings are properly popped.
850 - [Fytch](https://github.com/Fytch) found a bug in the documentation.
851 - [Jay Sistar](https://github.com/Type1J) implemented a Meson build description.
852 - [Henry Lee](https://github.com/HenryRLee) fixed a warning in ICC and improved the iterator implementation.
853 - [Vincent Thiery](https://github.com/vthiery) maintains a package for the Conan package manager.
854 - [Steffen](https://github.com/koemeet) fixed a potential issue with MSVC and `std::min`.
855 - [Mike Tzou](https://github.com/Chocobo1) fixed some typos.
856 - [amrcode](https://github.com/amrcode) noted a missleading documentation about comparison of floats.
857 - [Oleg Endo](https://github.com/olegendo) reduced the memory consumption by replacing `<iostream>` with `<iosfwd>`.
858 - [dan-42](https://github.com/dan-42) cleaned up the CMake files to simplify including/reusing of the library.
859 - [Nikita Ofitserov](https://github.com/himikof) allowed for moving values from initializer lists.
860 - [Greg Hurrell](https://github.com/wincent) fixed a typo.
861 - [Dmitry Kukovinets](https://github.com/DmitryKuk) fixed a typo.
862 - [kbthomp1](https://github.com/kbthomp1) fixed an issue related to the Intel OSX compiler.
863 - [Markus Werle](https://github.com/daixtrose) fixed a typo.
864 - [WebProdPP](https://github.com/WebProdPP) fixed a subtle error in a precondition check.
865
866
867 Thanks a lot for helping out! Please [let me know](mailto:mail@nlohmann.me) if I forgot someone.
868
869
870 ## Used third-party tools
871
872 The library itself contains 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!
873
874 - [**American fuzzy lop**](http://lcamtuf.coredump.cx/afl/) for fuzz testing
875 - [**AppVeyor**](https://www.appveyor.com) for [continuous integration](https://ci.appveyor.com/project/nlohmann/json) on Windows
876 - [**Artistic Style**](http://astyle.sourceforge.net) for automatic source code identation
877 - [**benchpress**](https://github.com/sbs-ableton/benchpress) to benchmark the code
878 - [**Catch**](https://github.com/philsquared/Catch) for the unit tests
879 - [**Clang**](http://clang.llvm.org) for compilation with code sanitizers
880 - [**Cmake**](https://cmake.org) for build automation
881 - [**Codacity**](https://www.codacy.com) for further [code analysis](https://www.codacy.com/app/nlohmann/json)
882 - [**cotire**](https://github.com/sakra/cotire) to speed of compilation
883 - [**Coveralls**](https://coveralls.io) to measure [code coverage](https://coveralls.io/github/nlohmann/json)
884 - [**Coverity Scan**](https://scan.coverity.com) for [static analysis](https://scan.coverity.com/projects/nlohmann-json)
885 - [**cppcheck**](http://cppcheck.sourceforge.net) for static analysis
886 - [**cxxopts**](https://github.com/jarro2783/cxxopts) to let benchpress parse command-line parameters
887 - [**Doxygen**](http://www.stack.nl/~dimitri/doxygen/) to generate [documentation](https://nlohmann.github.io/json/)
888 - [**git-update-ghpages**](https://github.com/rstacruz/git-update-ghpages) to upload the documentation to gh-pages
889 - [**Github Changelog Generator**](https://github.com/skywinder/github-changelog-generator) to generate the [ChangeLog](https://github.com/nlohmann/json/blob/develop/ChangeLog.md)
890 - [**libFuzzer**](http://llvm.org/docs/LibFuzzer.html) to implement fuzz testing for OSS-Fuzz
891 - [**OSS-Fuzz**](https://github.com/google/oss-fuzz) for continuous fuzz testing of the library
892 - [**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)
893 - [**Travis**](https://travis-ci.org) for [continuous integration](https://travis-ci.org/nlohmann/json) on Linux and macOS
894 - [**Valgrind**](http://valgrind.org) to check for correct memory management
895 - [**Wandbox**](http://melpon.org/wandbox) for [online examples](http://melpon.org/wandbox/permlink/4NEU6ZZMoM9lpIex)
896
897
898 ## Projects using JSON for Modern C++
899
900 The 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.
901
902
903 ## Notes
904
905 - The code contains numerous debug **assertions** which can be switched off by defining the preprocessor macro `NDEBUG`, see the [documentation of `assert`](http://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).
906 - 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.
907 - The library supports **Unicode input** as follows:
908   - 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).
909   - Other encodings such as Latin-1, UTF-16, or UTF-32 are not supported and will yield parse errors.
910   - [Unicode noncharacters](http://www.unicode.org/faq/private_use.html#nonchar1) will not be replaced by the library.
911   - Invalid surrogates (e.g., incomplete pairs such as `\uDEAD`) will yield parse errors.
912   - 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.
913 - The code can be compiled without C++ **runtime type identification** features; that is, you can use the `-fno-rtti` compiler flag.
914 - **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.
915 - 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) or [`nlohmann::fifo_map`](https://github.com/nlohmann/fifo_map).
916
917
918 ## Execute unit tests
919
920 To compile and run the tests, you need to execute
921
922 ```sh
923 $ make json_unit -Ctest
924 $ ./test/json_unit "*"
925
926 ===============================================================================
927 All tests passed (14504461 assertions in 48 test cases)
928 ```
929
930 Alternatively, you can use [CMake](https://cmake.org) and run
931
932 ```sh
933 $ mkdir build
934 $ cd build
935 $ cmake ..
936 $ make
937 $ ctest
938 ```
939
940 For more information, have a look at the file [.travis.yml](https://github.com/nlohmann/json/blob/master/.travis.yml).