You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

456 lines
21 KiB

  1. ![JSON for Modern C++](https://raw.githubusercontent.com/nlohmann/json/master/doc/json.gif)
  2. [![Build Status](https://travis-ci.org/nlohmann/json.svg?branch=master)](https://travis-ci.org/nlohmann/json)
  3. [![Build Status](https://ci.appveyor.com/api/projects/status/1acb366xfyg3qybk?svg=true)](https://ci.appveyor.com/project/nlohmann/json)
  4. [![Coverage Status](https://img.shields.io/coveralls/nlohmann/json.svg)](https://coveralls.io/r/nlohmann/json)
  5. [![Try online](https://img.shields.io/badge/try-online-blue.svg)](http://melpon.org/wandbox/permlink/wuiuqYiYqRTdI3rG)
  6. [![Documentation Status](https://img.shields.io/badge/docs-doxygen-blue.svg)](http://nlohmann.github.io/json)
  7. [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/nlohmann/json/master/LICENSE.MIT)
  8. [![Github Releases](https://img.shields.io/github/release/nlohmann/json.svg)](https://github.com/nlohmann/json/releases)
  9. [![Github Issues](https://img.shields.io/github/issues/nlohmann/json.svg)](http://github.com/nlohmann/json/issues)
  10. ## Design goals
  11. 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:
  12. - **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 know, what I mean.
  13. - **Trivial integration**. Our whole code consists of a single header file `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.
  14. - **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.
  15. Other aspects were not so important to us:
  16. - **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.
  17. - **Speed**. We currently implement the parser as naive [recursive descent parser](http://en.wikipedia.org/wiki/Recursive_descent_parser) with hand coded string handling. It is fast enough, but a [LALR-parser](http://en.wikipedia.org/wiki/LALR_parser) with a decent regular expression processor should be even faster (but would consist of more files which makes the integration harder).
  18. See the [contribution guidelines](https://github.com/nlohmann/json/blob/master/.github/CONTRIBUTING.md#please-dont) for more information.
  19. ## Integration
  20. 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
  21. ```cpp
  22. #include "json.hpp"
  23. // for convenience
  24. using json = nlohmann::json;
  25. ```
  26. 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).
  27. ## Supported compilers
  28. Though it's 2016 already, the support for C++11 is still a bit sparse. Currently, the following compilers are known to work:
  29. - GCC 4.9 - 6.0 (and possibly later)
  30. - Clang 3.4 - 3.9 (and possibly later)
  31. - Microsoft Visual C++ 14.0 RC (and possibly later)
  32. The code is currently checked with Travis for GCC 4.9, GCC
  33. I would be happy to learn about other compilers/versions.
  34. Please note:
  35. - 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.
  36. - 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.
  37. ```
  38. APP_STL := c++_shared
  39. NDK_TOOLCHAIN_VERSION := clang3.6
  40. APP_CPPFLAGS += -frtti -fexceptions
  41. ```
  42. - 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.
  43. The following compilers are currently used in [continuous integration](https://travis-ci.org/nlohmann/json):
  44. | Compiler | Operating System | Version String |
  45. |-----------------|------------------------------|----------------|
  46. | GCC 4.9.3 | Ubuntu 14.04.3 LTS | g++-4.9 (Ubuntu 4.9.3-8ubuntu2~14.04) 4.9.3 |
  47. | GCC 5.3.0 | Ubuntu 14.04.3 LTS | g++-5 (Ubuntu 5.3.0-3ubuntu1~14.04) 5.3.0 20151204 |
  48. | Clang 3.6.2 | Ubuntu 14.04.3 LTS | Ubuntu clang version 3.6.2-svn240577-1~exp1 (branches/release_36) (based on LLVM 3.6.2) |
  49. | Clang 3.7.1 | Ubuntu 14.04.3 LTS | Ubuntu clang version 3.7.1-svn253571-1~exp1 (branches/release_37) (based on LLVM 3.7.1) |
  50. | Clang 3.8.1 | Ubuntu 14.04.3 LTS | clang version 3.8.1-svn265380-1~exp1 (branches/release_38) |
  51. | Clang 3.9.0 | Ubuntu 14.04.3 LTS | clang version 3.9.0-svn267478-1~exp1 (trunk) |
  52. | Clang Xcode 6.1 | Darwin Kernel Version 13.4.0 | Apple LLVM version 6.0 (clang-600.0.54) (based on LLVM 3.5svn) |
  53. | Clang Xcode 6.2 | Darwin Kernel Version 13.4.0 | Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn) |
  54. | Clang Xcode 6.3 | Darwin Kernel Version 14.3.0 | Apple LLVM version 6.1.0 (clang-602.0.49) (based on LLVM 3.6.0svn) |
  55. | Clang Xcode 6.4 | Darwin Kernel Version 14.3.0 | Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn) |
  56. | Clang Xcode 7.1 | Darwin Kernel Version 14.5.0 | Apple LLVM version 7.0.0 (clang-700.1.76) |
  57. | Clang Xcode 7.2 | Darwin Kernel Version 15.0.0 | Apple LLVM version 7.0.2 (clang-700.1.81) |
  58. | Clang Xcode 7.3 | Darwin Kernel Version 14.5.0 | Apple LLVM version 7.3.0 (clang-703.0.29) |
  59. | Visual Studio 14 2015 | Windows Server 2012 R2 (x64) | Microsoft (R) Build Engine version 14.0.25123.0 |
  60. ## Examples
  61. Here are some examples to give you an idea how to use the class.
  62. Assume you want to create the JSON object
  63. ```json
  64. {
  65. "pi": 3.141,
  66. "happy": true,
  67. "name": "Niels",
  68. "nothing": null,
  69. "answer": {
  70. "everything": 42
  71. },
  72. "list": [1, 0, 2],
  73. "object": {
  74. "currency": "USD",
  75. "value": 42.99
  76. }
  77. }
  78. ```
  79. With the JSON class, you could write:
  80. ```cpp
  81. // create an empty structure (null)
  82. json j;
  83. // add a number that is stored as double (note the implicit conversion of j to an object)
  84. j["pi"] = 3.141;
  85. // add a Boolean that is stored as bool
  86. j["happy"] = true;
  87. // add a string that is stored as std::string
  88. j["name"] = "Niels";
  89. // add another null object by passing nullptr
  90. j["nothing"] = nullptr;
  91. // add an object inside the object
  92. j["answer"]["everything"] = 42;
  93. // add an array that is stored as std::vector (using an initializer list)
  94. j["list"] = { 1, 0, 2 };
  95. // add another object (using an initializer list of pairs)
  96. j["object"] = { {"currency", "USD"}, {"value", 42.99} };
  97. // instead, you could also write (which looks very similar to the JSON above)
  98. json j2 = {
  99. {"pi", 3.141},
  100. {"happy", true},
  101. {"name", "Niels"},
  102. {"nothing", nullptr},
  103. {"answer", {
  104. {"everything", 42}
  105. }},
  106. {"list", {1, 0, 2}},
  107. {"object", {
  108. {"currency", "USD"},
  109. {"value", 42.99}
  110. }}
  111. };
  112. ```
  113. 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:
  114. ```cpp
  115. // a way to express the empty array []
  116. json empty_array_explicit = json::array();
  117. // ways to express the empty object {}
  118. json empty_object_implicit = json({});
  119. json empty_object_explicit = json::object();
  120. // a way to express an _array_ of key/value pairs [["currency", "USD"], ["value", 42.99]]
  121. json array_not_object = { json::array({"currency", "USD"}), json::array({"value", 42.99}) };
  122. ```
  123. ### Serialization / Deserialization
  124. You can create an object (deserialization) by appending `_json` to a string literal:
  125. ```cpp
  126. // create object from string literal
  127. json j = "{ \"happy\": true, \"pi\": 3.141 }"_json;
  128. // or even nicer (thanks http://isocpp.org/blog/2015/01/json-for-modern-cpp)
  129. auto j2 = R"(
  130. {
  131. "happy": true,
  132. "pi": 3.141
  133. }
  134. )"_json;
  135. // or explicitly
  136. auto j3 = json::parse("{ \"happy\": true, \"pi\": 3.141 }");
  137. ```
  138. You can also get a string representation (serialize):
  139. ```cpp
  140. // explicit conversion to string
  141. std::string s = j.dump(); // {\"happy\":true,\"pi\":3.141}
  142. // serialization with pretty printing
  143. // pass in the amount of spaces to indent
  144. std::cout << j.dump(4) << std::endl;
  145. // {
  146. // "happy": true,
  147. // "pi": 3.141
  148. // }
  149. ```
  150. You can also use streams to serialize and deserialize:
  151. ```cpp
  152. // deserialize from standard input
  153. json j;
  154. std::cin >> j;
  155. // serialize to standard output
  156. std::cout << j;
  157. // the setw manipulator was overloaded to set the indentation for pretty printing
  158. std::cout << std::setw(4) << j << std::endl;
  159. ```
  160. These operators work for any subclasses of `std::istream` or `std::ostream`.
  161. 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.
  162. ### STL-like access
  163. 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.
  164. ```cpp
  165. // create an array using push_back
  166. json j;
  167. j.push_back("foo");
  168. j.push_back(1);
  169. j.push_back(true);
  170. // iterate the array
  171. for (json::iterator it = j.begin(); it != j.end(); ++it) {
  172. std::cout << *it << '\n';
  173. }
  174. // range-based for
  175. for (auto& element : j) {
  176. std::cout << element << '\n';
  177. }
  178. // getter/setter
  179. const std::string tmp = j[0];
  180. j[1] = 42;
  181. bool foo = j.at(2);
  182. // other stuff
  183. j.size(); // 3 entries
  184. j.empty(); // false
  185. j.type(); // json::value_t::array
  186. j.clear(); // the array is empty again
  187. // convenience type checkers
  188. j.is_null();
  189. j.is_boolean();
  190. j.is_number();
  191. j.is_object();
  192. j.is_array();
  193. j.is_string();
  194. // comparison
  195. j == "[\"foo\", 1, true]"_json; // true
  196. // create an object
  197. json o;
  198. o["foo"] = 23;
  199. o["bar"] = false;
  200. o["baz"] = 3.141;
  201. // special iterator member functions for objects
  202. for (json::iterator it = o.begin(); it != o.end(); ++it) {
  203. std::cout << it.key() << " : " << it.value() << "\n";
  204. }
  205. // find an entry
  206. if (o.find("foo") != o.end()) {
  207. // there is an entry with key "foo"
  208. }
  209. // or simpler using count()
  210. int foo_present = o.count("foo"); // 1
  211. int fob_present = o.count("fob"); // 0
  212. // delete an entry
  213. o.erase("foo");
  214. ```
  215. ### Conversion from STL containers
  216. 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.
  217. ```cpp
  218. std::vector<int> c_vector {1, 2, 3, 4};
  219. json j_vec(c_vector);
  220. // [1, 2, 3, 4]
  221. std::deque<double> c_deque {1.2, 2.3, 3.4, 5.6};
  222. json j_deque(c_deque);
  223. // [1.2, 2.3, 3.4, 5.6]
  224. std::list<bool> c_list {true, true, false, true};
  225. json j_list(c_list);
  226. // [true, true, false, true]
  227. std::forward_list<int64_t> c_flist {12345678909876, 23456789098765, 34567890987654, 45678909876543};
  228. json j_flist(c_flist);
  229. // [12345678909876, 23456789098765, 34567890987654, 45678909876543]
  230. std::array<unsigned long, 4> c_array {{1, 2, 3, 4}};
  231. json j_array(c_array);
  232. // [1, 2, 3, 4]
  233. std::set<std::string> c_set {"one", "two", "three", "four", "one"};
  234. json j_set(c_set); // only one entry for "one" is used
  235. // ["four", "one", "three", "two"]
  236. std::unordered_set<std::string> c_uset {"one", "two", "three", "four", "one"};
  237. json j_uset(c_uset); // only one entry for "one" is used
  238. // maybe ["two", "three", "four", "one"]
  239. std::multiset<std::string> c_mset {"one", "two", "one", "four"};
  240. json j_mset(c_mset); // only one entry for "one" is used
  241. // maybe ["one", "two", "four"]
  242. std::unordered_multiset<std::string> c_umset {"one", "two", "one", "four"};
  243. json j_umset(c_umset); // both entries for "one" are used
  244. // maybe ["one", "two", "one", "four"]
  245. ```
  246. Likewise, any associative key-value containers (`std::map`, `std::multimap`, `std::unordered_map`, `std::unordered_multimap`) whose keys are can construct an `std::string` and whose values can be used to construct JSON types (see examples above) can be used to 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.
  247. ```cpp
  248. std::map<std::string, int> c_map { {"one", 1}, {"two", 2}, {"three", 3} };
  249. json j_map(c_map);
  250. // {"one": 1, "three": 3, "two": 2 }
  251. std::unordered_map<const char*, double> c_umap { {"one", 1.2}, {"two", 2.3}, {"three", 3.4} };
  252. json j_umap(c_umap);
  253. // {"one": 1.2, "two": 2.3, "three": 3.4}
  254. std::multimap<std::string, bool> c_mmap { {"one", true}, {"two", true}, {"three", false}, {"three", true} };
  255. json j_mmap(c_mmap); // only one entry for key "three" is used
  256. // maybe {"one": true, "two": true, "three": true}
  257. std::unordered_multimap<std::string, bool> c_ummap { {"one", true}, {"two", true}, {"three", false}, {"three", true} };
  258. json j_ummap(c_ummap); // only one entry for key "three" is used
  259. // maybe {"one": true, "two": true, "three": true}
  260. ```
  261. ### Implicit conversions
  262. The type of the JSON object is determined automatically by the expression to store. Likewise, the stored value is implicitly converted.
  263. ```cpp
  264. /// strings
  265. std::string s1 = "Hello, world!";
  266. json js = s1;
  267. std::string s2 = js;
  268. // Booleans
  269. bool b1 = true;
  270. json jb = b1;
  271. bool b2 = jb;
  272. // numbers
  273. int i = 42;
  274. json jn = i;
  275. double f = jn;
  276. // etc.
  277. ```
  278. You can also explicitly ask for the value:
  279. ```cpp
  280. std::string vs = js.get<std::string>();
  281. bool vb = jb.get<bool>();
  282. int vi = jn.get<int>();
  283. // etc.
  284. ```
  285. ## License
  286. <img align="right" src="http://opensource.org/trademarks/opensource/OSI-Approved-License-100x137.png">
  287. The class is licensed under the [MIT License](http://opensource.org/licenses/MIT):
  288. Copyright &copy; 2013-2016 [Niels Lohmann](http://nlohmann.me)
  289. 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:
  290. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  291. 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.
  292. ## Thanks
  293. I deeply appreciate the help of the following people.
  294. - [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.
  295. - [elliotgoodrich](https://github.com/elliotgoodrich) fixed an issue with double deletion in the iterator classes.
  296. - [kirkshoop](https://github.com/kirkshoop) made the iterators of the class composable to other libraries.
  297. - [wancw](https://github.com/wanwc) fixed a bug that hindered the class to compile with Clang.
  298. - Tomas Åblad found a bug in the iterator implementation.
  299. - [Joshua C. Randall](https://github.com/jrandall) fixed a bug in the floating-point serialization.
  300. - [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.
  301. - [Daniel Kopeček](https://github.com/dkopecek) fixed a bug in the compilation with GCC 5.0.
  302. - [Florian Weber](https://github.com/Florianjw) fixed a bug in and improved the performance of the comparison operators.
  303. - [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.
  304. - [易思龙](https://github.com/likebeta) implemented a conversion from anonymous enums.
  305. - [kepkin](https://github.com/kepkin) patiently pushed forward the support for Microsoft Visual studio.
  306. - [gregmarr](https://github.com/gregmarr) simplified the implementation of reverse iterators and helped with numerous hints and improvements.
  307. - [Caio Luppi](https://github.com/caiovlp) fixed a bug in the Unicode handling.
  308. - [dariomt](https://github.com/dariomt) fixed some typos in the examples.
  309. - [Daniel Frey](https://github.com/d-frey) cleaned up some pointers and implemented exception-safe memory allocation.
  310. - [Colin Hirsch](https://github.com/ColinH) took care of a small namespace issue.
  311. - [Huu Nguyen](https://github.com/whoshuu) correct a variable name in the documentation.
  312. - [Silverweed](https://github.com/silverweed) overloaded `parse()` to accept an rvalue reference.
  313. - [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.
  314. - [ZahlGraf](https://github.com/ZahlGraf) added a workaround that allows compilation using Android NDK.
  315. - [whackashoe](https://github.com/whackashoe) replaced a function that was marked as unsafe by Visual Studio.
  316. - [406345](https://github.com/406345) fixed two small warnings.
  317. - [Glen Fernandes](https://github.com/glenfe) noted a potential portability problem in the `has_mapped_type` function.
  318. - [Corbin Hughes](https://github.com/nibroc) fixed some typos in the contribution guidelines.
  319. - [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.
  320. - [Volker Diels-Grabsch](https://github.com/vog) fixed a link in the README file.
  321. - [msm-](https://github.com/msm-) added support for american fuzzy lop.
  322. - [Annihil](https://github.com/Annihil) fixed an example in the README file.
  323. - [Themercee](https://github.com/Themercee) noted a wrong URL in the README file.
  324. - [Lv Zheng](https://github.com/lv-zheng) fixed a namespace issue with `int64_t` and `uint64_t`.
  325. - [abc100m](https://github.com/abc100m) analyzed the issues with GCC 4.8 and proposed a [partial solution](https://github.com/nlohmann/json/pull/212).
  326. - [zewt](https://github.com/zewt) added useful notes to the README file about Android.
  327. - [Róbert Márki](https://github.com/robertmrk) added a fix to use move iterators and improved the integration via CMake.
  328. - [Chris Kitching](https://github.com/ChrisKitching) cleaned up the CMake files.
  329. Thanks a lot for helping out!
  330. ## Notes
  331. - 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).
  332. - 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.
  333. ## Execute unit tests
  334. To compile and run the tests, you need to execute
  335. ```sh
  336. $ make
  337. $ ./json_unit "*"
  338. ===============================================================================
  339. All tests passed (5568705 assertions in 31 test cases)
  340. ```
  341. For more information, have a look at the file [.travis.yml](https://github.com/nlohmann/json/blob/master/.travis.yml).