in

nlohmann / json, Hacker News

nlohmann / json, Hacker News


                    

        

JSON for Modern C

Build StatusBuild StatusBuild StatusCoverage StatusCoverity Scan Build StatusCodacy BadgeLanguage grade: C/C  Fuzzing StatusTry onlineDocumentationGitHub licenseGitHub ReleasesGitHub IssuesAverage time to resolve an issueCII Best Practices

Design goals

There are myriads of (JSONlibraries out there, and each may even have its reason to exist. Our class had these design goals:

  • Intuitive syntax. In languages ​​such as Python, JSON feels like a first class data type. We used all the operator magic of modern C to achieve the same feeling in your code. Check out theexamples belowand you’ll know what I mean.

  • Trivial integration. Our whole code consists of a single header filejson.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.

  • Serious testing. Our class is heavilyunit-testedand covers100%of the code, including all exceptional behavior. Furthermore, we checked withValgrindand theClang Sanitizersthat there are no memory leaks. (Google OSS-Fuzz) additionally runs fuzz tests against all parsers 24 / 7, effectively executing billions of tests so far. To maintain high quality, the project is following theCore Infrastructure Initiative (CII) best practices.

Other aspects were not so important to us:

  • Memory efficiency. Each JSON object has an overhead of one pointer (the maximal size of a union) and one enumeration element (1 byte). The default generalization uses the following C data types:std :: stringfor strings,int 64 _t,uint 64 _tordoublefor numbers,std :: mapfor objects,std :: vectorfor arrays, andBoolfor Booleans. However, you can template the generalized classbasic_jsonto your needs.

  • (Speed) . There are certainlyfaster JSON librariesout 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 astd :: vectororSTD :: map, you are already set.

See thecontribution guidelinesfor more information.

Integration

json.hppis the single required file insingle_include / nlohmannorreleased here. You need to add

#includenlohmann / json.hpp>//for convenienceusingjson=nlohmann: : json;

to the files you want to process JSON and set the necessary switches to enable C 11 (eg,- std=c 11 (for GCC and Clang).

You can further use fileinclude / nlohmann / json_fwd.hppfor forward-declarations. The installation of json_fwd.hpp (as part of cmake's install step), can be achieved by setting- DJSON_MultipleHeaders=ON.

CMake

You can also use thenlohmann_json :: nlohmann_jsoninterface target in CMake. This target populates the appropriate usage requirements forINTERFACE_INCLUDE_DIRECTORIESto point to the appropriate include directories andINTERFACE_COMPILE_FEATURESfor the necessary C 11 flags.

External

To use this library from a CMake project, you can locate it directly withfind_package ()and use the namespaced imported target from the generated package configuration:

#CMakeLists.txtfind_package(nlohmann_json 3.2. 0REQUIRED) ...add_library(foo .. .) ...target_link_libraries(fooPRIVATE  (nlohmann_json :: nlohmann_json)

The package configuration file,nlohmann_jsonConfig.cmake, can be used either from an install tree or directly out of the build tree.

Supporting Both

To allow your project to support either an externally supplied or an embedded JSON library, you can use a pattern akin to the following:

#Top level CMakeLists.txt(project) ************************************************************************************************************************* (FOO) ...option(FOO_USE_EXTERNAL_JSON"Use an external JSON library"(OFF) ) ...add_subdirectory(thirdparty) ...add_library(foo .. .) ...#Note that the namespaced target will always be available regardless of the#import methodtarget_link_libraries(fooPRIVATE  (nlohmann_json :: nlohmann_json)
#Thirdparty / CMakeLists.txt...  (if)  (FOO_USE_EXTERNAL_JSON)   find_package(nlohmann_json 3.2. 0REQUIRED)else()   set(JSON_BuildTests  (OFF)CACHEINTERNAL"")   add_subdirectory(nlohmann_json)  (endif)  () ...

(thirdparty / nlohmann_json) is then a complete copy of this source tree.

Package Managers

🍺If you are using OS X andHomebrew, just typebrew tap nlohmann / jsonandbrew install nlohmann-jsonand you ' re set. If you want the bleeding edge rather than the latest release, usebrew install nlohmann-json --HEAD.

If you are using theMeson Build System, then you can get a wrap file by downloading it fromMeson WrapDB, or simply usemeson wrap install nlohmann_json.

If you are usingConanto manage your dependencies, merely addjsonformoderncpp / xyz @ vthiery / stableto your (conanfile.py) 's requires, whereXYZis the release version you want to use . Please file issueshereif you experience problems with the packages.

If you are usingSpack to manage your dependencies, you can use the(nlohmann-json) Package. Please see thespack projectfor any issues regarding the packaging.

If you are usinghunteron your project for external dependencies, then you can use thenlohmann_json package. Please see the hunter project for any issues regarding the packaging.

If you are using Buckaroo , you can install this library's module withbuckaroo add github.com/buckaroo-pm/nlohmann-json. Please file issueshere. There is a demo repohere.

If you are usingVCPGPon your project for external dependencies, then you can use thenlohmann-json package. Please see the vcpkg project for any issues regarding the packaging.

If you are usingcget, you can install the latest development version withcget install nlohmann / json. A specific version can be installed withcget install nlohmann/[email protected]. Also, the multiple header version can be installed by adding the- DJSON_MultipleHeaders=ONflag (ie,cget install nlohmann / json -DJSON_MultipleHeaders=ON).

If you are using (CocoaPods) , you can use the library by adding pod"nlohmann_json", '~>3.1.2'to your podfile (see (an example) ). Please file issueshere.

If you are usingNuGet, you can use the packagenlohmann.json. Please checkthis extensive descriptionon how to use the package. Please files issueshere.

If you are usingconda, you can use the packagenlohmann_jsonfromconda-forgeexecuting conda install -c conda-forge nlohmann_json

. Please file issueshere.

If you are usingMSYS2, your can use themingw-w 64 – nlohmann_jsonpackage, just typepacman -S mingw-w 64 - i 686 - nlohmann_jsonorpacman -S mingw-w 64 - x 86 _ 64 - nlohmann_jsonfor installation. Please file issueshereif you experience problems with the packages.

Examples

Beside the examples below, you may want to check thedocumentationwhere each function contains a separate code example (eg, check outemplace ()). All (example files) can be compiled and executed on their own (eg, file (emplace.cpp) ).

JSON as first-class data type

Here are some examples to give you an idea how to use the class.

Assume you want to create the JSON object

{   " (Pi)  "(*************************************************************************************************************************:  3. 141,   "happy"(*************************************************************************************************************************:  (true) ,   "name"(*************************************************************************************************************************:" (Niels)  ",   "nothing"(*************************************************************************************************************************:  (null) ,   "answer": {     "everything"(*************************************************************************************************************************:42  },   " (list)  ": [1,0,2],   "object": {     "currency"(*************************************************************************************************************************:" (USD)  ",     "value":42.  } }

With this library, you could write:

//create an empty structure (null)json j;//add a number that is stored as double (note the implicit conversion of j to an object)j ["pi"]=3. 141;//add a Boolean that is stored as boolj ["happy"]=(true) ;//add a string that is stored as std :: stringJ ["name"]=" (Niels)  ";//add another null object by passing nullptrJ ["nothing"]=nullptr;//add an object inside the objectJ ["answer"] ["everything"]=42;//add an array that is stored as std :: vector (using an initializer list)j ["list"]={ (1) ,  (0) ,  (2) };//add another object (using an initializer list of pairs)j ["object"]={{"currency"," (USD)  "}, {"value",42. 99}};//instead, you could also write (which looks very similar to the JSON above)json j2={   {" (PI)  ",3. 141},   {" (happy)  ",true},   {" (name)  ","Niels"},   {"nothing",nullptr} ,   {"answer", {     {"everything",42}   }},   {" (list)  ", { (1) ,  (0) ,  (2) }},   {"object", {     {"currency","USD"},     {" (value)  ",42. 99}   }} };

Note that in all these cases, you never need to “tell” the compiler which JSON value type you want to use. If you want to be explicit or express some edge cases, the functionsjson :: array ()andjson :: object ()will help:

//a way to express the empty array []json empty_array_explicit=json :: array ();//ways to express the empty object {}json empty_object_implicit=json ({}); json empty_object_explicit=json :: object ();//a way to express an _array_ of key / value pairs [["currency", "USD"], ["value", 42.99]]json array_not_object=json :: array ({{"currency",''USD"}, {""value",42.}});

Serialization / Deserialization

To / from strings

You can create a JSON value (deserialization) by appending_JSONto a string literal:

//create object from string literaljson j="{ " (happy)   ": true, " (PI)   ": 3. 141}"_ json;//or even nicer with a raw string literal(auto) ************************************************************************************************************************* (J2=)   (R "){"happy": true,"PI": 3. 141}) "_ json;

Note that without appending the_JSONsuffix, the passed string literal is not parsed, but just used as JSON string value. That is,json j="{" happy ": true, " pi ": 3. 141} "would just store the string"{" happy " : true, "pi": 3. 141} "rather than parsing the actual object.

The above example can also be expressed explicitly usingjson :: parse ():

//parse explicitly(auto)  j3=json: : parse ("{ " (happy)   "(*************************************************************************************************************************: true, "Pi ": 3. 141}"");

You can also get a string representation of a JSON value (serialize):

//explicit conversion to stringstd :: string s=j.dump ();//{ "happy ": true,  "pi ": 3. 141}//serialization with pretty printing//pass in the amount of spaces to indentstd :: cout//{//"happy": true,//"PI": 3. 141//}

Note the difference between serialization and assignment:

//store a string in a JSON valuejson j_string="this is a string";//retrieve the string value(auto)  cpp_string=j_string. get<:string>();//retrieve the string value (alternative when an variable already exists)std :: string cpp_string2; j_string.get_to (cpp_string2);//retrieve the serialized value (explicit JSON serialization)std :: string serialized_string=j_string.dump ();//output of original stringstd :: cout"=="""==""()' n'';//output of serialized valuestd :: cout"=="

.dump ()always returns the serialized value, and. ()returns the originally stored string value.

Note the library only supports UTF-8. When you store strings with different encodings in the library, callingdump ()may throw an exception unlessjson :: error_handler_t :: replaceorjson :: error_handler_t :: ignoreare used as error handlers.

To / from streams (eg files, string streams)

You can also use streams to serialize and deserialize:

//deserialize from standard inputjson j; std :: cin>>j;//serialize to standard outputstd :: cout//the setw manipulator was overloaded to set the indentation for pretty printingstd :: cout

These operators work for any subclasses ofstd :: istreamorstd :: ostream. Here is the same example with files:

//read a JSON filestd :: ifstream  (i)  ("file.json"); json j; i>>j;//write prettified JSON to another filestd :: ofstream  (o)  (" (pretty.json)  "); o

Please note that setting the exception bit forfailbitis inappropriate for this use case. It will result in program termination due to thenoexceptspecifier in use.

Read from iterator range

You 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 astd :: vector<:uint8_t>:

std :: vectoruint8_t>v={'t',''r'',' (U)  ',''  (e)  ''}; json j=json :: parse (v.begin (), v.end ());

You may leave the iterators for the range [begin, end):

std::vector<:>uint8_t>v={'t','r','u','e'};json j=json::parse(v);

SAX interface

The library uses a SAX-like interface with the following functions:

//called when null is parsedboolnull();//called when a boolean is parsed; value is passedboolboolean(boolval);//called when a signed or unsigned integer number is parsed; value is passedboolnumber_integer(number_integer_tval);boolnumber_unsigned(number_unsigned_tval);//called when a floating-point number is parsed; value and original string is passedboolnumber_float(number_float_tval,conststring_t& s);//called when a string is parsed; value is passed and can be safely moved awayboolstring(string_t& val);//called when an object or array begins or ends, resp. The number of elements is passed (or -1 if not known)boolstart_object(std::size_telements);boolend_object();boolstart_array(std::size_telements);boolend_array();//called when an object key is parsed; value is passed and can be safely moved awayboolkey(string_t& val);//called when a parse error occurs; byte position, the last token, and an exception is passedboolparse_error(std::size_tposition,conststd::string& last_token,constdetail::exception& ex);

The return value of each function determines whether parsing should proceed.

To implement your own SAX handler, proceed as follows:

  1. Implement the SAX interface in a class. You can use classnlohmann::json_saxas base class, but you can also use any class where the functions described above are implemented and public.
  2. Create an object of your SAX interface class, e.g.my_sax.
  3. Callbool json::sax_parse(input, &my_sax); where the first parameter can be any input like a string or an input stream and the second parameter is a pointer to your SAX interface.

Note thesax_parsefunction only returns aboolindicating the result of the last executed SAX event. It does not return ajsonvalue – 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 yourparse_errorimplementation. Internally, the SAX interface is used for the DOM parser (classjson_sax_dom_parser) as well as the acceptor (json_sax_acceptor), see filejson_sax.hpp.

STL-like access

We designed the JSON class to behave just like an STL container. In fact, it satisfies theReversibleContainerrequirement.

//create an array using push_backjson j;j.push_back("foo");j.push_back(1);j.push_back(true);//also use emplace_backj.emplace_back(1.78);//iterate the arrayfor(json::iterator it=j.begin(); it !=j.end();   it) {  std::cout'n';}//range-based forfor(auto& element : j) {  std::cout'n';}//getter/setterconstautotmp=j[0] .Get<:string>(); J [1]=42;  (bool)  foo=j. at ( (2) );//  (comparison)  J=="["foo", 1, true]"_ json;//  (true) //other stuffj.size ();//  (3 entries)  j.empty ();//  (false)  j.type ();//json :: value_t :: arrayj.clear ();//the array is empty again//convenience type checkersj.is_null (); j.is_boolean (); j.is_number (); j.is_object (); j.is_array (); j.is_string ();//create an objectjson o; o ["foo"]=23; o ["bar"]=(false) ; o ["baz"]=(***************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************);//also use emplaceo.emplace ("Weather","Sunny");//special iterator member functions for objectsfor(json :: iterator it=o.begin (); it!=o.end ();    it) {   std :: coutkey()":"value()" n"; }//the same code as range forfor( (auto) ************************************************************************************************************************* (& el: o.items) )) {   std :: coutkey()":"value()" n"; }//even easier with structured bindings (C    17)for( (auto)  & [key, value]: o.items ()) {   std :: cout":""" n"; }//find an entry(if)  (o.find (" (foo)  ")!=o.end ()) {   //there is an entry with key "foo"}//or simpler using count ()intfoo_present=o. count (" (foo)  ");//  (1)intfob_present=o. count (" (FOB)  ");//  (0) //delete an entryo.erase (" (foo)  ");

Conversion from STL containers

Any sequence container (std :: array,std :: vector,std :: deque, (std :: forward_list) ,std :: list) whose values can be used to construct JSON values ​​(eg, integers, floating point numbers, Booleans, string types, or again STL containers described in this section) can be used to create a JSON array. The same holds for similar associative containers (std :: set,std :: multiset,std :: unordered_set,std :: unordered_multiset), but in these cases the order of the elements of the array depends on how the elements are ordered in the respective STL container.

std :: vectorint>c_vector { (1) ,  (2) ,  (3) ,  (4) }; JSONj_vec(c_vector) ;//[1, 2, 3, 4]std :: dequec_deque { (1.2)  ,  (2.3) ,  (3.4) ,  (5.6) }; JSONj_deque(c_deque) ;//[1.2, 2.3, 3.4, 5.6]std :: listc_list { (true)  ,  (true) ,  (false) ,  (true) }; JSON  (j_list)  (c_list) ;//[true, true, false, true]std :: forward_listint 64 _t>c_flist {12345678909876,23456789098765,34567890987654,45678909876543}; JSONj_flist(c_flist) ;//[12345678909876, 23456789098765, 34567890987654, 45678909876543]std :: arrayc_array {{ (1) ,  (2) ,  (3) ,  (4) }}; JSONj_array(c_array) ;//[1, 2, 3, 4]std :: set<:string>c_set {""  (one)  ",""two"," (three)  ","Four"," (one)  "}; JSON  (j_set)  (c_set) ;//only one entry for "one" is used//["four", "one", "three", "two"]std :: unordered_set<:string>c_uset {""  (one)  "," (two)  ",""Three""," (four)  ","one""}; JSONj_uset(c_uset) ;//only one entry for "one" is used//  (maybe ["two", "three", "four", "one"])   std :: multiset<:string>c_mset {""  (one)  "," (two)  "," (one)  ",""Four""}; JSONj_mset(c_mset) ;//both entries for "one" are used//  (maybe ["one", "two", "one", "four"]   std :: unordered_multiset<:string>c_umset {""  (one)  "," (two)  "," (one)  ",""  (four)  "}; JSONj_umset(c_umset) ;//both entries for "one" are used//  (maybe ["one", "two", "one", "four"]

Likewise, any associative key-value containers (std :: map,std :: multimap,std :: unordered_map,std :: unordered_multimap) whose keys can construct anstd :: stringand whose values ​​can be used to construct JSON values (see examples above) can be used to create a JSON object. Note that in case of multimaps only one key is used in the JSON object and the value depends on the internal order of the STL container.

std :: mapint>c_map {{"One",  (1) }, {" (two)  ",  (2) }, {""Three",  (3) }}; JSONj_map(c_map) ;//{"one": 1, "three": 3, "two": 2}std :: unordered_mapchar  (*,) ************************************************************************************************************************ (double)>c_umap {{""  (one)  ",  (1.2) }, {" (two)  ",  (2.3) }, {""Three",  (3.4) }}; JSONj_umap(c_umap) ;//{"one": 1.2, "two": 2.3, "three": 3.4}std :: multimapBool>c_mmap {{" (one)  ",  (true) }, {" (two)  "",  (true) }, {""Three",  (false) }, {"Three",  (true) }}; JSONj_mmap(c_mmap) ;//only one entry for key "three" is used//maybe {"one": true, "two": true, "three": true}std :: unordered_multimapBool>c_ummap {{" (one)  ",true}, {"two'',true}, {" (three)  ",  (false) }, {"three",  (true) }}; JSONj_ummap(c_ummap) ;//only one entry for key "three" is used//maybe {"one": true, "two": true, "three": true}

JSON Pointer and JSON Patch

The library supports (JSON Pointer) (RFC 6901) as alternative means to address structured values. On top of this,JSON Patch( (RFC) ) allows to describe differences between two JSON values ​​- effectively allowing patch and diff operations known from Unix.

//a JSON valuejson j_original=(R "){"baz": ["one", "two", "three"],"foo": "bar"}) "_ json;//access members with a JSON pointer (RFC 6901)j_original ["/baz/1"_json_pointer];//"two"//  (a JSON patch) RFC 6902)json j_patch=(R ")[{ "op": "replace", "path": "/baz", "value": "boo" },{ "op": "add", "path": "/hello", "value": ["world"]},{"op": "remove", "path": "/ foo"}]) "_ json;//apply the patchjson j_result=j_original.patch (j_patch);//{//"baz": "boo",//"Hello": ["world"]//}//calculate a JSON patch from two JSON values ​​json :: diff( j_result, j_original);//[//{"op": "replace", "path": "/ baz", "value": ["one", "two", "three"]},//{"op": "remove", "path": "/ hello"},//{"op": "add", "path": "/ foo", "value": "bar"}//]

JSON Merge Patch

The library supports (JSON Merge Patch) (RFC 7386) as a patch format. Instead of using JSON Pointer (see above) to specify values ​​to be manipulated, it describes the changes using a syntax that closely mimics the document being modified.

//a JSON valuejson j_document=(R "){"a": "b","C": {"d": "e","f": "g"}}) "_ json;//  (a patch)  json j_patch=(R "){"a": "z","C": {"f": null}}) "_ json;//apply the patchj_document.merge_patch (j_patch);//{//"a": "z",//"c": {//"d": "e"//}//}

Implicit conversions

Supported types can be implicitly converted to JSON values.

It is recommended toNOT USEimplicit conversions (FROM) a JSON value. You can find more details about this recommendationhere

//stringsstd :: string s1="Hello, world!"; json js=s1;  (auto)  s2=js. get<:string>();//  (NOT RECOMMENDED)  std :: string s3=js; std :: string s4; s4=js;//  (Booleans)   (bool) ************************************************************************************************************************* (B1=) ************************************************************************************************************************ (true) ; json jb=b1;  (auto)  b2=jb. get();//  (NOT RECOMMENDED)   (bool)  b3=jb;  (bool)  B4; b4=jb;//  (numbers)int  (i=)  42; json jn=i;  (auto)  f=jn. getdouble>();//  (NOT RECOMMENDED)   (double)  f2=jb;  (double)  F3; f3=jb;//  (etc.)

Note thatchartypes are not automatically converted to JSON strings, but to integer numbers. A conversion to a string must be specified explicitly:

charch=''  (A)  ';//  (ASCII value)json j_default=ch;//stores integer number 65json j_string=std :: string ( (1) , ch);//stores string "A"

Arbitrary types conversions

Every type can be serialized in JSON, not just STL containers and scalar types. Usually, you would do something along those lines:

namespacens{     //a simple struct to model a person    structperson{         std :: string name;         std :: string address;         intage;     }; }  ns :: person p={"Ned Flanders","744 Evergreen Terrace",60};//convert to JSON: copy each value into the JSON objectjson j; j ["name"]=p.name; j ["address"]=p.address; j ["age"]=p.age;//...//convert from JSON: copy each value from the JSON objectns :: person p {     J ["name"].get<:string>(),     J ["address"].get<:string>(),     J ["age"].getint>() };

It works, but that’s quite a lot of boilerplate. .. Fortunately, there’s a better way:

//create a personns :: person p {"Ned Flanders","744 Evergreen Terrace",60};//conversion: person ->jsonjson j=p;  std :: cout//{"address": "744 Evergreen Terrace "," age ": 60, "name": "Ned Flanders"}//conversion: json ->person(auto)  p2=j. get<:person>();//that's itassert(p==p2);

Basic usage

To make this work with one of your types, you only need to provide two functions:

usingnlohmann :: json;namespacens{      (void)to_json(json & j,  (const)  person & p) {         j=json {{"  (name)  ", p.name}, {"address", p.address}, {"age", p.age}};     }       (void)from_json( (const)  json & j, person & p) {         J.at(" (name)  ").get_to(P.name);         J.at("address").get_to(p.address);         J.at(" (age)  ").get_to  (p.  (age) );     } }//namespace ns

That’s all! When calling the (JSON) constructor with your type, your custom (to_json) method will be automatically called. Likewise, when callingget()or (get_to) your_type &), thefrom_jsonmethod will be called.

Some important things:

  • Those methodsMUSTbe 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 namespacens, wherepersonis defined).
  • Those methodsMUST (be available) eg, proper headers must be included) everywhere you use these conversions. Look atissue 1108for errors that may occur otherwise.
  • When usingget(),your_type(MUST) beDefaultConstructible. (There is a way to bypass this requirement described later.)
  • (In function) from_json, use function(at ()to access the object values ​​rather thanoperator []. In case a key does not exist,atthrows an exception that you can handle, whereasoperator []exhibits undefined behavior.

  • You do not need to add serializers or deserializers for STL types likestd :: vector: the library already implements these.

How do I convert third-party types?

This requires a bit more advanced technique. But first, let’s see how this conversion mechanism works:

The library uses (JSON Serializers) to convert types to json. The default serializer fornlohmann :: jsonisnlohmann :: adl_serializer(ADL meansArgument-Dependent Lookup).

It is implemented like this (simplified):

templateTypename  (T)structadl_serializer{     staticvoidto_json(json & j,constT & value) {         //calls the "to_json" method in T's namespace    }      staticvoidfrom_json(constjson & j, T & value) {         //same thing, but with the "from_json" method    } };

This serializer works fine when you have control over the type’s namespace. However, what aboutboost :: optionalorstd :: filesystem :: path(C 17)? Hijacking theboostnamespace is pretty bad, and it’s illegal to add something other than template specializations toSTD

To solve this, you need to add a specialization ofadl_serializerto thenlohmannnamespace, here’s an example:

//partial specialization (full specialization works too)namespacenlohmann{     template    structadl_serializer>{         staticvoidto_json(json & j,constboost :: optional& opt) {              (if)  (opt==boost :: none) {                 J=nullptr;             }  (else)  {               j=* opt;//this will call adl_serializer:: to_json which will                        //find the free function to_json in T's namespace!            }         }          staticvoidfrom_json(constjson & j, boost :: optional& opt) {              (if)  (j. ************************************************************************************************************************ (is_null)  ()) {                 opt=boost :: none;             }  (else)  {                 opt=j.get();//same as above, but with                                  //adl_serializer:: from_json            }         }     }; }

There is a way, if your type isMoveConstructible. You will need to specialize theadl_serializeras well, but with a special (from_json) overload:

structmove_only_type{     move_only_type()=delete;     move_only_type( (int) ************************************************************************************************************************* (ii): i (ii) {}     move_only_type( (const)  move_only_type &)=delete;     move_only_type(move_only_type &&)=default;      inti; };namespacenlohmann{     template    structadl_serializer{         //note: the return type is no longer 'void', and the method only takes        //one argument        staticmove_only_typefrom_json( (const)  json & j) {             return  ({j.)  getint>()};         }          //Here's the catch! You must provide a to_json method! Otherwise you        //will not be able to convert move_only_type to json, since you fully        //specialized adl_serializer on that type        staticvoidto_json(json & j, move_only_type t) {             j=t.  (i)  ;         }     }; }

Can I write my own serializer? (Advanced use)

Yes. You might want to take a look atunit-udt.cppin the test suite, to see a few examples.

If you write your own serializer, you’ll need to do a few things:

  • Use a differentbasic_jsonalias than [key, value] nlohmann :: json(the last template parameter ofbasic_jsonis the (JSONSerializer) )
  • use yourbasic_jsonalias (or a template parameter) in all yourto_json/from_jsonMethods
  • usenlohmann :: to_jsonandnlohmann :: from_jsonwhen you need ADL

Here is an example, without simplifications, that only accepts types with a size

//You should use void as a second template argument//if you don't need compile-time checks on TtemplateSizeof(T)32>:: type>structless_than _ 32 _ serializer{     template    staticvoidto_json(BasicJsonType & j, T value) {         //we want to use ADL, and call the correct to_json overload        usingnlohmann :: to_json ;//this method is called by adl_serializer,                                 //this is where the magic happens        to_json(j, value );     }      template    staticvoidfrom_json(constBasicJsonType & j, T & value) {         //same thing here        usingnlohmann :: from_json ;         from_json(j, value );     } };

Beverycareful when reimplementing your serializer, you can stack overflow if you don’t pay attention:

templateTypename  (T,  (void)>structbad_serializer{     template    staticvoidto_json(BasicJsonType & j,constT & value) {       //this calls BasicJsonType :: json_serializer:: to_json (j, value);      //if BasicJsonType :: json_serializer==bad_serializer ... oops!      j=value;     }      template    staticvoidto_json(constBasicJsonType & j, T & value) {       //this calls BasicJsonType :: json_serializer:: from_json (j, value);      //if BasicJsonType :: json_serializer==bad_serializer ... oops!      value=j.templateget();//  (oops!)      } };

Specializing enum conversion

By default, enum values ​​are serialized to JSON as integers . In some cases this could result in undesired behavior. If an enum is modified or re-ordered after data has been serialized to JSON, the later de-serialized JSON data may be undefined or a different enum value than was originally intended.

It is possible to more precisely specify how a given enum is mapped to and from JSON as shown below:

//example enum type declaration(enum)  TaskState {     TS_STOPPED,     TS_RUNNING,     TS_COMPLETED,     TS_INVALID=-  (1) , };//map TaskState values ​​to JSON as stringsNLOHMANN_JSON_SERIALIZE_ENUM(TaskState, {     {TS_INVALID,nullptr} ,     {TS_STOPPED,"stopped"},     {TS_RUNNING," (running)  "},     {TS_COMPLETED," (completed)  "}, })

TheNLOHMANN_JSON_SERIALIZE_ENUM ()macro declares a set ofto_json ()/from_json ()functions for type (TaskState) while avoiding repetition and boilerplate serilization code.

Usage:

//enum to JSON as stringjson j=TS_STOPPED;assert(J=="stopped");//json string to enumjson j3=" (running)  ";assert(j3.get()==TS_RUNNING);//undefined json value to enum (where the first map entry above is the default)json jPi=(3.) ;assert(jPi.get()==TS_INVALID);

Just as inArbitrary Type Conversionsabove,

  • NLOHMANN_JSON_SERIALIZE_ENUM ()MUST be declared in your enum type’s namespace (which can be the global namespace), or the library will not be able to locate it and it will default to integer serialization.
  • It MUST be available (eg, proper headers must be included) everywhere you use the conversions.

Other Important points:

  • When usingget(), undefined JSON values ​​will default to the first pair specified in your map. Select this default pair carefully.
  • If an enum or JSON value is specified more than once in your map, the first matching occurrence from the top of the map will be returned when converting to or from JSON.

Binary formats (BSON, CBOR, MessagePack, and UBJSON)

Though JSON is a ubiquitous data format, it is not a very compact format suitable for data exchange, for instance over a network. Hence, the library supports (BSON) (Binary JSON), (CBOR) (Concise Binary Object Representation),MessagePack, and (UBJSON) (Universal Binary JSON Specification) to efficiently encode JSON values ​​to byte vectors and to decode such vectors.

//create a JSON valuejson j=(R "){"compact": true, "schema": 0}) "_ json;//serialize to BSONstd :: vectoruint8_t>v_bson=json :: to_bson (j);//  (0x1B, 0x) , 0x 00, 0x 00, 0x  (, 0x) , 0x6F, 0x6D, 0x 70, 0x 61, 0x 63, 0x 74, 0x 00, 0x 01, 0x 10, 0x 73, 0x 63, 0x 68, 0x 65, 0x6D, 0x 61, 0x 00, 0x 00, 0x 00, 0x 00, 0x 00, 0x 00//  (Roundtrip)  json j_from_bson=json :: from_bson (v_bson);//serialize to CBORstd :: vectoruint8_t>v_cbor=json :: to_cbor (j);//  (0xA2, 0x) , 0x 63, 0x6F, 0x6D, 0x 70, 0x 61, 0x 63, 0x 74, 0xF5, 0x 66, 0x 73, 0x 63, 0x 68, 0x 65, 0x6D, 0x 61, 0x 00//  (Roundtrip)  json j_from_cbor=json :: from_cbor (v_cbor);//serialize to MessagePackstd :: vectoruint8_t>v_msgpack=json :: to_msgpack (j);//  (0x) , 0xA7, 0x 63, 0x6F, 0x6D, 0x 70, 0x 61, 0x 63, 0x 74, 0xC3, 0xA6, 0x 73, 0x 63, 0x 68, 0x 65, 0x6D, 0x 61, 0x 00//  (Roundtrip)  json j_from_msgpack=json :: from_msgpack (v_msgpack);//serialize to UBJSONstd :: vectoruint8_t>v_ubjson=json :: to_ubjson (j);//  (0x7B, 0x) , 0x  (, 0x) , 0x6F, 0x6D, 0x 70, 0x 61, 0x 63, 0x 74, 0x 54, 0x 69, 0x 06, 0x 73, 0x 63, 0x 68, 0x 65, 0x6D, 0x 61, 0x 69, 0x 00, 0x7D//  (Roundtrip)  json j_from_ubjson=json :: from_ubjson (v_ubjson);

Supported compilers

Though it’s 2019 already, the support for C 11 is still a bit sparse. Currently, the following compilers are known to work:

  • GCC 4.8 – 9.0 (and possibly later)
  • Clang 3.4 – 8.0 (and possibly later)
  • (Intel C Compiler) .0.2 (and possibly later)

  • Microsoft Visual C 2015 / Build Tools 14 .0. 25123 .0 (and possibly later)
  • Microsoft Visual C 2017 / Build Tools 15 .5. 180. 51428 (and possib ly later)

I would be happy to learn about other compilers / versions.

Please note:

  • GCC 4.8 has a bug57824): multiline raw strings cannot be the arguments t o macros. Don’t use multiline raw strings directly in macros with this compiler.

  • 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.

    APP_STL:=c    _ shared NDK_TOOLCHAIN_VERSION:=clang3.6 APP_CPPFLAGS =-frtti -fexceptions

    The code compiles successfully with (Android NDK) , Revision 9 – 11 (and possibly later) andCrystaX’s Android NDKversion 10.

  • For GCC running on MinGW or Android SDK, the error'to_string' is not a member of 'std'(or similarly, forstrtod) 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 tothis siteandthis discussionfor information on how to fix this bug. For Android NDK usingAPP_STL:=gnustl_static, please refer tothis discussion.

  • Unsupported versions of GCC and Clang are rejected by# errordirectives. This can be switched off by definingJSON_SKIP_UNSUPPORTED_COMPILER_CHECK. Note that you can expect no support in this case.

The following compilers are currently used in continuous integration at (Travis) ,AppVeyor, and (Doozer) :

(GCC 4.8.5) (Ubuntu) . 04 .5 LTS

(GCC 4.8.5) (CentOS Release-7-6.) 2.el7.centos.x 86 _ 64 (g ​​ ) GCC (4.8.5) (Red Hat 4.8.5 – 36)

(g ​​ ) Raspbian 4.9.2 – deb8u2 (4.9.2)

(GCC 4.9.4) (Ubuntu) . 04 1 LTS

(Ubuntu) . (LTS) (g ​​ ) Ubuntu / Linaro 5.3.1 – (ubuntu2 (5.3.1)

(GCC 5.5.0) (Ubuntu) . 04 1 LTS (g ​​ – 5) Ubuntu 5.5.0 – 12 ubuntu1 ~ 14. 04) 5.5.0 20171010(GCC 6.3.1) (Fedora release) (Twenty Four) (g ​​ ) GCC (6.3.1) (Red Hat 6.3.1-1)(GCC 6.4.0) (Ubuntu) . 04 1 LTS (g ​​ – 6) Ubuntu 6.4.0 – 17 ubuntu1 ~ 14. 04) 6.4.0 20180424(GCC 7.3.0) (Ubuntu) . 04 1 LTS (g ​​ – 7) Ubuntu 7.3.0 – 21 ubuntu1 ~ 14. 04) 7.3.0(GCC 7.3.0) (Windows Server) *********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************** (R2) x 64) (g ​​ ) x 86 _ 64 – posix-seh-rev0 , Built by MinGW-W 64 project (7.3.0)(GCC 8.1.0) (Ubuntu) . 04 1 LTS

(Ubuntu) . 04 1 LTS

(clang version 3.6.2-svn) – 1 ~ exp1 (branches / release _ 36 (based on LLVM 3.6.2)

(Ubuntu) . 04 1 LTS (clang version 3.7.1-svn) – 1 ~ exp1 (branches / release _ 37 (based on LLVM 3.7.1)

(Ubuntu) . 04 1 LTS

(Ubuntu) . 04 1 LTS

(Ubuntu) . 04 1 LTS (clang version 4.0.1-svn) – 1 ~ exp1 (branches / release _ 40)

(Ubuntu) . 04 1 LTS (clang version 5.0.2-svn) – 1 (exp1) 20180509123505. 100 (branches / release _ 50)

(Ubuntu) . 04 1 LTS (clang version 6.0.1-svn) – 1 (exp1) 85 (branches / release _ 60)

(Ubuntu) . 04 1 LTS (clang version 7.0.1-svn) – 1 (exp1) 20181213084532. 54 (branches / release _ 70)

(OSX) . 11 .6 (Apple LLVM version 8.1.0 (clang – (***********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************. )

(OSX) . 12 .6 (Apple LLVM version 9.0.0 (clang – .0. 37)

(OSX) . 12 .6 (Apple LLVM version 9.0.0 (clang – .0. 38)

(OSX) . 13 .3

(OSX) . 13 .3

(OSX) . 13 .3 (Apple LLVM version) ************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************** 0.0 (clang – 1000. 11. 45. 2)

(OSX) . 13 .3 (Apple LLVM version) ************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************** 0.0 (clang – 1000. 11. 45. 5)

(Windows Server) *********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************** (R2) x 64) (Microsoft (R) Build Engine version) ********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************** .0. 1, MSVC .0. 24215 .1

(Windows Server) (Microsoft (R) Build Engine version) ********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************* 7. . 61344, MSVC 19. 14. 26433 .0

Compiler Operating System Version String
g – 4.8 (Ubuntu 4.8.5-2ubuntu1 ~ 14. 04 .2 (4.8.5)
GCC 4.9.2 (armv7l) Raspbian GNU / Linux 8 (jessie)
g – 4.9 (Ubuntu 4.9.4-2ubuntu1 ~ 14. ******************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************** 1) 4.9.4
GCC 5.3.1 (armv7l)
g – 8 (Ubuntu 8.1.0-5ubuntu1 ~ 14. 04 8.1.0
Clang 3.5.0 clang version 3.5.0-4ubuntu2 ~ trusty2 (tags / RELEASE _ 350 / final) (based on LLVM 3.5.0)
Clang 3.6.2 Ubuntu 14. 04 1 LTS
Clang 3.7.1
Clang 3.8.0 clang version 3.8.0-2ubuntu3 ~ trusty5 (tags / RELEASE _ 380 / final)
Clang 3.9.1 clang version 3.9.1-4ubuntu3 ~ 14. 3. Tags / RELEASE _ 391 / RC2)
Clang 4.0.1
Clang 5.0.2
Clang 6.0.1
Clang 7.0.1
Clang Xcode 8.3
Clang Xcode 9.0
Clang Xcode 9.1
Clang Xcode 9.2 Apple LLVM version 9.1.0 (clang – 902 .0 39 1)
Clang Xcode 9.3 Apple LLVM version 9.1.0 (clang – 902 .0 39 2)
Clang Xcode 10 .0
Clang Xcode 10 .1
Visual Studio 14 2015
Visual Studio 2017

License

The class is licensed under the (MIT License) *****************************************:

Copyright © 2013 – 2019 Niels Lohmann

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:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

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.


The class contains the UTF-8 Decoder from Bjoern Hoehrmann which is licensed under theMIT Licensesee above). Copyright © 2008 – 2009Björn Hoehrmann([email protected]) [list]

The class contains a slightly modified version of the Grisu2 algorithm from Florian Loitsch which is licensed under theMIT License(see above). Copyright © 2009Florian Loitsch

The class contains a copy ofHedleyfrom Evan Nemerson which is licensed as (CC0-1.0) .

open an issue at GitHub. 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 theclosed issues, you will see that we react quite timely in most cases.

Only if your request would contain confidential information, pleasesend me an email. For encrypted messages, please usethis key.

Security

Commits by Niels Lohmannandreleasesare signed with this (PGP Key

Thanks

I deeply appreciate the help of the following people.

  • Teemperorimplemented CMake support and lcov integration, realized escape and Unicode handling in the string parser, and fixed the JSON serialization.
  • elliotgoodrichfixed an issue with double deletion in the iterator classes.
  • Kirkshoopmade the iterators of the class composable to other libraries.
  • wancwfixed a bug that hindered the class to compile with
  • Tomas Åblad found a bug in the iterator implementation.
  • Randallfixed a bug in the floating -point serialization.
  • Aaron Burghardtimplemented 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.
  • Daniel Kopečekfixed a bug in the compilation with GCC 5.0.
  • Florian Weberfixed a bug in and improved the performance of the comparison operators.
  • (Eric Corneliuspointed out a bug in the handling with NaN and infinity values. He also improved the performance of the string escaping.
  • 易 思龙implemented a conversion from anonymous enums.
  • Kepkinpatiently pushed forward the support for Microsoft Visual studio.
  • gregmarrsimplified the implementation of reverse iterators and helped with numerous hints and improvements. In particular, he pushed forward the implementation of user-defined types.
  • Caio Luppifixed a bug in the Unicode handling.
  • dariomtfixed some typos in the examples.
  • Daniel Freycleaned up some pointers and implemented exception-safe memory allocation.
  • Colin Hirschtook care of a small namespace issue.
  • Huu Nguyencorrect a variable name in the documentation.
  • Silverweedoverloaded (parse))to accept an rvalue reference.
  • dariomtfixed a subtlety in MSVC type support and implemented theget_ref ()function to get a reference to stored values.
  • ZahlGrafadded a workaround that allows compilation using Android NDK.
  • whackashoereplaced a function that was marked as unsafe by Visual Studio.
  • 406345fixed two small warnings.
  • Glen Fernandesnoted a potential portability problem in thehas_mapped_typefunction.
  • Corbin Hughesfixed some typos in the contribution guidelines.
  • Twelsbyfixed 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.
  • (Volker Diels-Grabsch) fixed a link in the README file.
  • msm –added support for American Fuzzy Lop.
  • (Annihil) fixed an example in the README file.
  • Themerceenoted a wrong URL in the README file.
  • (Lv Zheng) fixed a namespace issue withint 64 _tand (uint) ************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************* (_T) .
  • (ABC) ********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************** (M) analyzed the issues with GCC 4.8 and proposed apartial solution.
  • Zewtadded useful notes to the README file about Android.
  • Róbert Márki added a fix to use move iterators and improved the integration via CMake.
  • Chris Kitchingcleaned up the CMake files.
  • Tom Needhamfixed a subtle bug with MSVC 2015 which was also proposed byMichael K..
  • Mário Feroldifixed a small typo.
  • duncanwernerfound a really embarrassing performance regression in the 2.0.0 release.
  • (Damien) fixed one of the last conversion warnings.
  • Thomas Braunfixed a warning in a test case.
  • (Théo DELRIEU) patiently and constructively oversaw the long way toward (iterator-range parsing) . He also implemented the magic behind the serialization / deserialization of user-defined types and split the single header file into smaller chunks.
  • Stefanfixed a minor issue in the documentation.
  • Vasil Dimovfixed the documentation regarding conversions fromSTD :: multiset.
  • ChristophJudoverworked the CMake files to ease project inclusion.
  • Vladimir Petrigo (made a SFINAE hack more readable and added Visual Studio) to the build matrix.
  • Denis Andrejewfixed a grammar issue in the README file.
  • Pierre-Antoine Lacazefound a subtle bug in thedump () (function.)
  • TurpentineDistillerypointed tostd :: 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.
  • cgzoneshad an idea how to fix the Coverity scan.
  • Jared Grubbsilenced a nasty documentation warning.
  • (Yixin Zhang) fixed an integer overflow check.
  • (Bosswestfalen) ***************************************** (merged two iterator classes into a smaller one.)
  • (Daniel) helped to get Travis execute the tests with Clang's sanitizers.
  • Jonathan Leefixed an example in the README file .
  • gnzlbgsupported the implementation of user-defined types.
  • Alexej Harmhelped to get the user -defined types working with Visual Studio.
  • Jared Grubbsupported the implementation of user-defined types.
  • (EnricoBillanoted a typo in an example.
  • Martin Hořeňovskýfound a way for a 2x speedup for the compilation time of the test suite.
  • ukheggfound proposed an improvement for the examples section.
  • rswanson-ihinoted a typo in the README.
  • Mihai Stanfixed a bug in the comparison withnullptrs.
  • Tushar Maheshwari (added) cotiresupport to speed up the compilation.
  • TedLyngmonoted a typo in the README, removed unnecessary bit arithmetic, and fixed some- Weffc (Warnings.)
  • Krzysztof Wośmade exceptions more visible.
  • ftillierfixed a compiler warning.
  • Tinloafmade sure all pushed warnings are properly popped.
  • Fytchfound a bug in the documentation.
  • Jay Sistarimplemented a Meson build description.
  • Henry Leefixed a warning in ICC and improved the iterator implementation.
  • Vincent Thierymaintains a package for the Conan package manager.
  • Steffenfixed a potential issue with MSVC andstd :: min.
  • (Mike Tzou) fixed some typos.
  • amrcodenoted a misleading documentation about comparison of floats.
  • (Oleg Endo) reduced the memory consumption by replacingwith.
  • dan - 42cleaned up the CMake files to simplify including / reusing of the library.
  • Nikita Ofitserovallowed for moving values ​​from initializer lists.
  • Greg Hurrellfixed a typo.
  • Dmitry Kukovinetsfixed a typo.
  • kbthomp1fixed an issue related to the Intel OSX compiler.
  • Markus Werle fixed a typo.
  • WebProdPPfixed a subtle error in a precondition check.
  • (Alex) noted an error in a code sample.
  • Tom de Geusreported some warnings with ICC and helped fixing them.
  • Perry Kundertsimplified reading from input streams.
  • Sonu Lohanifixed a small compilation error.
  • Jamie Seward fixed all MSVC warnings.
  • Nate Vargasadded a Doxygen tag file.
  • pvleuvenhelped fixing a warning in ICC.
  • Pavelhelped fixing some warnings in MSVC.
  • Jamie Sewardavoided unnecessary string copies in (find ()
  • andcount ().

  • Mitjafixed some typos.
  • Jorrit Wronskiupdated the Hunter package links.
  • Matthias Mölleradded anatvisfor the MSVC debug view.
  • bogemicfixed some C 17 deprecation warnings.
  • Eren Okka fixed some MSVC warnings.
  • ABOLZintegrated the Grisu2 algorithm for proper floating-point formatting, allowing more roundtrip checks to succeed.
  • (Vadim Evard) fixed a Markdown issue in the README.
  • Zerodefectfixed a compiler warning.
  • (Kert) allowed to template the string type in the serialization and added the possibility to override the exceptional behavior.
  • (mark - 99helped fixing an ICC error.
  • (Patrik Huber) ***************************************** (fixed links in the README file.)
  • (johnfb) found a bug in the implementation of CBOR's indefinite length strings.
  • Paul Fultz IIadded a note on the cget package manager.
  • Wilson Linmade the integration section of the README more concise.
  • (RalfBielig) detected and fixed a memory leak in the parser callback.
  • agrianiusallowed to dump JSON to an alternative string type.
  • Kevin Tononoverworked the C 11 compiler checks in CMake.
  • Axel Hueblsimplified a CMake check and added support for theSpack package manager.
  • Carlos O'Ryanfixed a typo.
  • James Upjohnfixed a version number in the compilers section.
  • Chuck Atkinsadjusted the CMake files to the CMake packaging guidelines and provided documentation for the CMake integration.
  • Jan Schöppach fixed a typo.
  • martin-mfgfixed a typo.
  • Matthias Möllerremoved the dependency fromstd :: stringstream.
  • agrianiusadded code to use alternative string implementations.
  • (Daniel) allowed to use more algorithms with theitems ()function.
  • Julius Rakowfixed the Meson include directory and fixed the links tocppreference.com.
  • Sonu Lohanifixed the compilation with MSVC 2015 in debug mode.
  • (Grembo) fixed the test suite and re-enabled several test cases.
  • Hyeon Kimintroduced the macroJSON_INTERNAL_CATCHto control the exception handling inside the library.
  • Thyufixed a compiler warning.
  • David Guthriefixed a subtle compilation error with Clang 3.4.2.
  • (Dennis Fischer) allowed to callfind_packagewithout installing the library.
  • Hyeon Kim fixed an issue with a double macro definition.
  • Ben Bermanmade some error messages more understandable.
  • Zakalibitfixed a compilation problem with the Intel C compiler.
  • Mandreyelfixed a compilation problem.
  • Kostiantyn Ponomarenkoadded version and license information to the Meson build file.
  • Henry Schreineradded support for GCC 4.8.
  • (knilch) made sure the test suite does not stall when run in the wrong directory.
  • Antonio Borondo (fixed an MSVC) warning.
  • Dan Gendreauimplemented theNLOHMANN_JSON_SERIALIZE_ENUMmacro to quickly define a enum / JSON mapping.
  • EFPadded line and column information to parse errors.
  • Julian-Beckeradded BSON support.
  • Pratik Chowdhuryadded support for structured bindings.
  • David Avedissianadded support for Clang 5.0.1 (PS4 version).
  • Jonathan Dumaresqimplemented an input adapter to read from (FILE ***************************************************************************************************************).
  • KJPUSfixed a link in the documentation.
  • Manvendra Singhfixed a typo in the documentation.
  • Ziggurat 29fixed an MSVC warning.
  • Sylvain Corlayadded code to avoid an issue with MSVC.
  • Mefylfixed a bug when JSON was parsed from an input stream.
  • Millian Poquetallowed to install the library via Meson.
  • Michael Behrns-Millerfound an issue with a missing namespace.
  • Nasztanovics Ferencfixed a compilation issue with libc 2. 12.
  • Andreas Schwabfixed the endian conversion.
  • Mark-Dunning fixed a warning in MSVC.
  • Gareth Sylvester-Bradley added (operator /) for JSON Pointers.
  • (John-Mark) noted a missing header.
  • Vitaly Zaitsevfixed compilation with GCC 9.0.
  • Laurent Stacul fixed compilation with GCC 9.0.
  • (Ivor Wanders) helped reducing the CMake requirement to version 3.1.
  • (njlr) updated the Buckaroo instructions.
  • (Lion) fixed a compilation issue with GCC 7 on CentOS .
  • Isaac Nickaeinimproved the integer serilization performance and implemented Thecontains ()function.
  • past -duesuppressed an unfixable warning.
  • Elvis Oricimproved Meson support.
  • (Matěj Plch) fixed an example in the README.
  • Mark Beckwithfixed a typo .
  • scinartfixed bug in the serializer.
  • Patrick Boettcherimplementedpush_back ()and (pop_back ()
  • for JSON Pointers.

  • Bruno Oliveiraadded support for Conda.
  • Michele Caini (fixed links in the README.
  • (Hani) documented how to install the library with NuGet.
  • Mark Beckwithfixed a typo .
  • yann-morin – 1998helped reducing the CMake requirement to version 3.1.
  • Konstantin Podsvirovmaintains a package for the MSYS2 software distro.
  • remyabeladded GNUInstallDirs to the CMake files.
  • Taylor Howardfixed a unit test.
  • Gabe Ronimplemented theto_stringmethod.
  • (Watal M. Iwasaki) fixed a Clang warning.
  • Viktor Kirilovswitched the unit tests from Catch todoctest

Thanks a lot for helping out! Pleaselet me knowif I forgot someone.

Used third-party tools

The 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!

Projects using JSON for Modern C

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.

Character encoding

The library supports (Unicode input) as follows:

  • Only (UTF-8) encoded input is supported which is the default encoding for JSON according toRFC 8259.
  • STD :: U (string) andstd :: u (string) can be parsed, assuming UTF - 16 and UTF - 32 encoding, respectively. These encodings are not supported when reading from files or other input containers.
  • Other encodings such as Latin-1 or ISO 8859 – 1 arenotsupported and will yield parse or serialization errors.
  • Unicode noncharacterswill not be replaced by the library.
  • Invalid surrogates (eg, incomplete pairs such as uDEAD) will yield parse errors.
  • 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.
  • When you store strings with different encodings in the library, callingdump ()may throw an exception unlessjson :: error_handler_t :: replaceorjson :: error_handler_t :: ignoreare used as error handlers.

Comments in JSON

This library does not support comments. It does so for three reasons:

  1. Comments are not part of theJSON specification. You may argue that//or/ ** /are allowed in JavaScript, but JSON is not JavaScript.

  2. This was not an oversight: Douglas Crockfordwrote on thisin May 2012:

    I removed comments from JSON because I saw people were using them to hold parsing directives, a practice which would have destroyed interoperability. I know that the lack of comments makes some people sad, but it shouldn’t.

    Suppose you are using JSON to keep configuration files, which you would like to annotate. Go ahead and insert all the comments you like. Then pipe it through JSMin before handing it to your JSON parser.

  3. It is dangerous for interoperability if some libraries would add comment support while others don’t. Please checkThe Harmful Consequences of the Robustness Principleon this.

This library will not support comments in the future. If you wish to use comments, I see three options:

  1. Strip comments before using this library.
  2. Use a different JSON library with comment support.
  3. Use a format that natively supports comments (eg, YAML or JSON5).

Order of object keys

By default, the library does not preserve theinsertion order of object elements. This is standards-compliant, as theJSON standarddefines 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 liketsl :: ordered_map(integration) ornlohmann :: fifo_map(integration).

  • documentation ofassert. In particular, noteoperator []implementsunchecked accessfor const objects: If the given key is not present, the behavior is undefined (think of a dereferenced null pointer) and yields anassertion failureif assertions are switched on. If you are not sure whether an element in an object exists, use checked access with the(at ()function.
  • As the exact type of a number is not defined in theJSON specification, 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)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.
  • The code can be compiled without C runtime type identificationfeatures; that is, you can use the- fno-rtticompiler flag.
  • Exceptionsare used widely within the library. They can, however, be switched off with either using the compiler flag- fno-exceptionsor by defining the symbolJSON_NOEXCEPTION. In this case, exceptions are replaced by an (abort))call.

Execute unit tests

To compile and run the tests, you need to execute

$ mkdir build $  (CD)  build $ cmake .. $ cmake --build.$ ctest --output-on-failure

For more information, have a look at the file.travis.yml.

  

Brave Browser
Read MorePayeer

What do you think?

Leave a Reply

Your email address will not be published. Required fields are marked *

GIPHY App Key not set. Please check settings

Strictly Come Dancing: Neil Jones and Alex Scott raise the roof with their 'chemistry' – Daily Mail, Daily Mail

Strictly Come Dancing: Neil Jones and Alex Scott raise the roof with their 'chemistry' – Daily Mail, Daily Mail

Text Rendering Hates You, Hacker News