2
0

json.hpp 190 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220
  1. // __ _____ _____ _____
  2. // __| | __| | | | JSON for Modern C++
  3. // | | |__ | | | | | | version 3.11.2
  4. // |_____|_____|_____|_|___| https://github.com/nlohmann/json
  5. //
  6. // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me>
  7. // SPDX-License-Identifier: MIT
  8. /****************************************************************************\
  9. * Note on documentation: The source files contain links to the online *
  10. * documentation of the public API at https://json.nlohmann.me. This URL *
  11. * contains the most recent documentation and should also be applicable to *
  12. * previous versions; documentation for deprecated functions is not *
  13. * removed, but marked deprecated. See "Generate documentation" section in *
  14. * file docs/README.md. *
  15. \****************************************************************************/
  16. #ifndef INCLUDE_NLOHMANN_JSON_HPP_
  17. #define INCLUDE_NLOHMANN_JSON_HPP_
  18. #include <algorithm> // all_of, find, for_each
  19. #include <cstddef> // nullptr_t, ptrdiff_t, size_t
  20. #include <functional> // hash, less
  21. #include <initializer_list> // initializer_list
  22. #ifndef JSON_NO_IO
  23. #include <iosfwd> // istream, ostream
  24. #endif // JSON_NO_IO
  25. #include <iterator> // random_access_iterator_tag
  26. #include <memory> // unique_ptr
  27. #include <string> // string, stoi, to_string
  28. #include <utility> // declval, forward, move, pair, swap
  29. #include <vector> // vector
  30. #include <nlohmann/adl_serializer.hpp>
  31. #include <nlohmann/byte_container_with_subtype.hpp>
  32. #include <nlohmann/detail/conversions/from_json.hpp>
  33. #include <nlohmann/detail/conversions/to_json.hpp>
  34. #include <nlohmann/detail/exceptions.hpp>
  35. #include <nlohmann/detail/hash.hpp>
  36. #include <nlohmann/detail/input/binary_reader.hpp>
  37. #include <nlohmann/detail/input/input_adapters.hpp>
  38. #include <nlohmann/detail/input/lexer.hpp>
  39. #include <nlohmann/detail/input/parser.hpp>
  40. #include <nlohmann/detail/iterators/internal_iterator.hpp>
  41. #include <nlohmann/detail/iterators/iter_impl.hpp>
  42. #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  43. #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
  44. #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  45. #include <nlohmann/detail/json_custom_base_class.hpp>
  46. #include <nlohmann/detail/json_pointer.hpp>
  47. #include <nlohmann/detail/json_ref.hpp>
  48. #include <nlohmann/detail/macro_scope.hpp>
  49. #include <nlohmann/detail/string_concat.hpp>
  50. #include <nlohmann/detail/string_escape.hpp>
  51. #include <nlohmann/detail/meta/cpp_future.hpp>
  52. #include <nlohmann/detail/meta/type_traits.hpp>
  53. #include <nlohmann/detail/output/binary_writer.hpp>
  54. #include <nlohmann/detail/output/output_adapters.hpp>
  55. #include <nlohmann/detail/output/serializer.hpp>
  56. #include <nlohmann/detail/value_t.hpp>
  57. #include <nlohmann/json_fwd.hpp>
  58. #include <nlohmann/ordered_map.hpp>
  59. #if defined(JSON_HAS_CPP_17)
  60. #include <any>
  61. #include <string_view>
  62. #endif
  63. /*!
  64. @brief namespace for Niels Lohmann
  65. @see https://github.com/nlohmann
  66. @since version 1.0.0
  67. */
  68. NLOHMANN_JSON_NAMESPACE_BEGIN
  69. /*!
  70. @brief a class to store JSON values
  71. @internal
  72. @invariant The member variables @a m_value and @a m_type have the following
  73. relationship:
  74. - If `m_type == value_t::object`, then `m_value.object != nullptr`.
  75. - If `m_type == value_t::array`, then `m_value.array != nullptr`.
  76. - If `m_type == value_t::string`, then `m_value.string != nullptr`.
  77. The invariants are checked by member function assert_invariant().
  78. @note ObjectType trick from https://stackoverflow.com/a/9860911
  79. @endinternal
  80. @since version 1.0.0
  81. @nosubgrouping
  82. */
  83. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  84. class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions)
  85. : public ::nlohmann::detail::json_base_class<CustomBaseClass>
  86. {
  87. private:
  88. template<detail::value_t> friend struct detail::external_constructor;
  89. template<typename>
  90. friend class ::nlohmann::json_pointer;
  91. // can be restored when json_pointer backwards compatibility is removed
  92. // friend ::nlohmann::json_pointer<StringType>;
  93. template<typename BasicJsonType, typename InputType>
  94. friend class ::nlohmann::detail::parser;
  95. friend ::nlohmann::detail::serializer<basic_json>;
  96. template<typename BasicJsonType>
  97. friend class ::nlohmann::detail::iter_impl;
  98. template<typename BasicJsonType, typename CharType>
  99. friend class ::nlohmann::detail::binary_writer;
  100. template<typename BasicJsonType, typename InputType, typename SAX>
  101. friend class ::nlohmann::detail::binary_reader;
  102. template<typename BasicJsonType>
  103. friend class ::nlohmann::detail::json_sax_dom_parser;
  104. template<typename BasicJsonType>
  105. friend class ::nlohmann::detail::json_sax_dom_callback_parser;
  106. friend class ::nlohmann::detail::exception;
  107. /// workaround type for MSVC
  108. using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
  109. using json_base_class_t = ::nlohmann::detail::json_base_class<CustomBaseClass>;
  110. JSON_PRIVATE_UNLESS_TESTED:
  111. // convenience aliases for types residing in namespace detail;
  112. using lexer = ::nlohmann::detail::lexer_base<basic_json>;
  113. template<typename InputAdapterType>
  114. static ::nlohmann::detail::parser<basic_json, InputAdapterType> parser(
  115. InputAdapterType adapter,
  116. detail::parser_callback_t<basic_json>cb = nullptr,
  117. const bool allow_exceptions = true,
  118. const bool ignore_comments = false
  119. )
  120. {
  121. return ::nlohmann::detail::parser<basic_json, InputAdapterType>(std::move(adapter),
  122. std::move(cb), allow_exceptions, ignore_comments);
  123. }
  124. private:
  125. using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
  126. template<typename BasicJsonType>
  127. using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
  128. template<typename BasicJsonType>
  129. using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
  130. template<typename Iterator>
  131. using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
  132. template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
  133. template<typename CharType>
  134. using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
  135. template<typename InputType>
  136. using binary_reader = ::nlohmann::detail::binary_reader<basic_json, InputType>;
  137. template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
  138. JSON_PRIVATE_UNLESS_TESTED:
  139. using serializer = ::nlohmann::detail::serializer<basic_json>;
  140. public:
  141. using value_t = detail::value_t;
  142. /// JSON Pointer, see @ref nlohmann::json_pointer
  143. using json_pointer = ::nlohmann::json_pointer<StringType>;
  144. template<typename T, typename SFINAE>
  145. using json_serializer = JSONSerializer<T, SFINAE>;
  146. /// how to treat decoding errors
  147. using error_handler_t = detail::error_handler_t;
  148. /// how to treat CBOR tags
  149. using cbor_tag_handler_t = detail::cbor_tag_handler_t;
  150. /// helper type for initializer lists of basic_json values
  151. using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
  152. using input_format_t = detail::input_format_t;
  153. /// SAX interface type, see @ref nlohmann::json_sax
  154. using json_sax_t = json_sax<basic_json>;
  155. ////////////////
  156. // exceptions //
  157. ////////////////
  158. /// @name exceptions
  159. /// Classes to implement user-defined exceptions.
  160. /// @{
  161. using exception = detail::exception;
  162. using parse_error = detail::parse_error;
  163. using invalid_iterator = detail::invalid_iterator;
  164. using type_error = detail::type_error;
  165. using out_of_range = detail::out_of_range;
  166. using other_error = detail::other_error;
  167. /// @}
  168. /////////////////////
  169. // container types //
  170. /////////////////////
  171. /// @name container types
  172. /// The canonic container types to use @ref basic_json like any other STL
  173. /// container.
  174. /// @{
  175. /// the type of elements in a basic_json container
  176. using value_type = basic_json;
  177. /// the type of an element reference
  178. using reference = value_type&;
  179. /// the type of an element const reference
  180. using const_reference = const value_type&;
  181. /// a type to represent differences between iterators
  182. using difference_type = std::ptrdiff_t;
  183. /// a type to represent container sizes
  184. using size_type = std::size_t;
  185. /// the allocator type
  186. using allocator_type = AllocatorType<basic_json>;
  187. /// the type of an element pointer
  188. using pointer = typename std::allocator_traits<allocator_type>::pointer;
  189. /// the type of an element const pointer
  190. using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
  191. /// an iterator for a basic_json container
  192. using iterator = iter_impl<basic_json>;
  193. /// a const iterator for a basic_json container
  194. using const_iterator = iter_impl<const basic_json>;
  195. /// a reverse iterator for a basic_json container
  196. using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
  197. /// a const reverse iterator for a basic_json container
  198. using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
  199. /// @}
  200. /// @brief returns the allocator associated with the container
  201. /// @sa https://json.nlohmann.me/api/basic_json/get_allocator/
  202. static allocator_type get_allocator()
  203. {
  204. return allocator_type();
  205. }
  206. /// @brief returns version information on the library
  207. /// @sa https://json.nlohmann.me/api/basic_json/meta/
  208. JSON_HEDLEY_WARN_UNUSED_RESULT
  209. static basic_json meta()
  210. {
  211. basic_json result;
  212. result["copyright"] = "(C) 2013-2022 Niels Lohmann";
  213. result["name"] = "JSON for Modern C++";
  214. result["url"] = "https://github.com/nlohmann/json";
  215. result["version"]["string"] =
  216. detail::concat(std::to_string(NLOHMANN_JSON_VERSION_MAJOR), '.',
  217. std::to_string(NLOHMANN_JSON_VERSION_MINOR), '.',
  218. std::to_string(NLOHMANN_JSON_VERSION_PATCH));
  219. result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR;
  220. result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR;
  221. result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH;
  222. #ifdef _WIN32
  223. result["platform"] = "win32";
  224. #elif defined __linux__
  225. result["platform"] = "linux";
  226. #elif defined __APPLE__
  227. result["platform"] = "apple";
  228. #elif defined __unix__
  229. result["platform"] = "unix";
  230. #else
  231. result["platform"] = "unknown";
  232. #endif
  233. #if defined(__ICC) || defined(__INTEL_COMPILER)
  234. result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
  235. #elif defined(__clang__)
  236. result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
  237. #elif defined(__GNUC__) || defined(__GNUG__)
  238. result["compiler"] = {{"family", "gcc"}, {"version", detail::concat(
  239. std::to_string(__GNUC__), '.',
  240. std::to_string(__GNUC_MINOR__), '.',
  241. std::to_string(__GNUC_PATCHLEVEL__))
  242. }
  243. };
  244. #elif defined(__HP_cc) || defined(__HP_aCC)
  245. result["compiler"] = "hp"
  246. #elif defined(__IBMCPP__)
  247. result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
  248. #elif defined(_MSC_VER)
  249. result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
  250. #elif defined(__PGI)
  251. result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
  252. #elif defined(__SUNPRO_CC)
  253. result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
  254. #else
  255. result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
  256. #endif
  257. #if defined(_MSVC_LANG)
  258. result["compiler"]["c++"] = std::to_string(_MSVC_LANG);
  259. #elif defined(__cplusplus)
  260. result["compiler"]["c++"] = std::to_string(__cplusplus);
  261. #else
  262. result["compiler"]["c++"] = "unknown";
  263. #endif
  264. return result;
  265. }
  266. ///////////////////////////
  267. // JSON value data types //
  268. ///////////////////////////
  269. /// @name JSON value data types
  270. /// The data types to store a JSON value. These types are derived from
  271. /// the template arguments passed to class @ref basic_json.
  272. /// @{
  273. /// @brief default object key comparator type
  274. /// The actual object key comparator type (@ref object_comparator_t) may be
  275. /// different.
  276. /// @sa https://json.nlohmann.me/api/basic_json/default_object_comparator_t/
  277. #if defined(JSON_HAS_CPP_14)
  278. // use of transparent comparator avoids unnecessary repeated construction of temporaries
  279. // in functions involving lookup by key with types other than object_t::key_type (aka. StringType)
  280. using default_object_comparator_t = std::less<>;
  281. #else
  282. using default_object_comparator_t = std::less<StringType>;
  283. #endif
  284. /// @brief a type for an object
  285. /// @sa https://json.nlohmann.me/api/basic_json/object_t/
  286. using object_t = ObjectType<StringType,
  287. basic_json,
  288. default_object_comparator_t,
  289. AllocatorType<std::pair<const StringType,
  290. basic_json>>>;
  291. /// @brief a type for an array
  292. /// @sa https://json.nlohmann.me/api/basic_json/array_t/
  293. using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
  294. /// @brief a type for a string
  295. /// @sa https://json.nlohmann.me/api/basic_json/string_t/
  296. using string_t = StringType;
  297. /// @brief a type for a boolean
  298. /// @sa https://json.nlohmann.me/api/basic_json/boolean_t/
  299. using boolean_t = BooleanType;
  300. /// @brief a type for a number (integer)
  301. /// @sa https://json.nlohmann.me/api/basic_json/number_integer_t/
  302. using number_integer_t = NumberIntegerType;
  303. /// @brief a type for a number (unsigned)
  304. /// @sa https://json.nlohmann.me/api/basic_json/number_unsigned_t/
  305. using number_unsigned_t = NumberUnsignedType;
  306. /// @brief a type for a number (floating-point)
  307. /// @sa https://json.nlohmann.me/api/basic_json/number_float_t/
  308. using number_float_t = NumberFloatType;
  309. /// @brief a type for a packed binary type
  310. /// @sa https://json.nlohmann.me/api/basic_json/binary_t/
  311. using binary_t = nlohmann::byte_container_with_subtype<BinaryType>;
  312. /// @brief object key comparator type
  313. /// @sa https://json.nlohmann.me/api/basic_json/object_comparator_t/
  314. using object_comparator_t = detail::actual_object_comparator_t<basic_json>;
  315. /// @}
  316. private:
  317. /// helper for exception-safe object creation
  318. template<typename T, typename... Args>
  319. JSON_HEDLEY_RETURNS_NON_NULL
  320. static T* create(Args&& ... args)
  321. {
  322. AllocatorType<T> alloc;
  323. using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
  324. auto deleter = [&](T * obj)
  325. {
  326. AllocatorTraits::deallocate(alloc, obj, 1);
  327. };
  328. std::unique_ptr<T, decltype(deleter)> obj(AllocatorTraits::allocate(alloc, 1), deleter);
  329. AllocatorTraits::construct(alloc, obj.get(), std::forward<Args>(args)...);
  330. JSON_ASSERT(obj != nullptr);
  331. return obj.release();
  332. }
  333. ////////////////////////
  334. // JSON value storage //
  335. ////////////////////////
  336. JSON_PRIVATE_UNLESS_TESTED:
  337. /*!
  338. @brief a JSON value
  339. The actual storage for a JSON value of the @ref basic_json class. This
  340. union combines the different storage types for the JSON value types
  341. defined in @ref value_t.
  342. JSON type | value_t type | used type
  343. --------- | --------------- | ------------------------
  344. object | object | pointer to @ref object_t
  345. array | array | pointer to @ref array_t
  346. string | string | pointer to @ref string_t
  347. boolean | boolean | @ref boolean_t
  348. number | number_integer | @ref number_integer_t
  349. number | number_unsigned | @ref number_unsigned_t
  350. number | number_float | @ref number_float_t
  351. binary | binary | pointer to @ref binary_t
  352. null | null | *no value is stored*
  353. @note Variable-length types (objects, arrays, and strings) are stored as
  354. pointers. The size of the union should not exceed 64 bits if the default
  355. value types are used.
  356. @since version 1.0.0
  357. */
  358. union json_value
  359. {
  360. /// object (stored with pointer to save storage)
  361. object_t* object;
  362. /// array (stored with pointer to save storage)
  363. array_t* array;
  364. /// string (stored with pointer to save storage)
  365. string_t* string;
  366. /// binary (stored with pointer to save storage)
  367. binary_t* binary;
  368. /// boolean
  369. boolean_t boolean;
  370. /// number (integer)
  371. number_integer_t number_integer;
  372. /// number (unsigned integer)
  373. number_unsigned_t number_unsigned;
  374. /// number (floating-point)
  375. number_float_t number_float;
  376. /// default constructor (for null values)
  377. json_value() = default;
  378. /// constructor for booleans
  379. json_value(boolean_t v) noexcept : boolean(v) {}
  380. /// constructor for numbers (integer)
  381. json_value(number_integer_t v) noexcept : number_integer(v) {}
  382. /// constructor for numbers (unsigned)
  383. json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
  384. /// constructor for numbers (floating-point)
  385. json_value(number_float_t v) noexcept : number_float(v) {}
  386. /// constructor for empty values of a given type
  387. json_value(value_t t)
  388. {
  389. switch (t)
  390. {
  391. case value_t::object:
  392. {
  393. object = create<object_t>();
  394. break;
  395. }
  396. case value_t::array:
  397. {
  398. array = create<array_t>();
  399. break;
  400. }
  401. case value_t::string:
  402. {
  403. string = create<string_t>("");
  404. break;
  405. }
  406. case value_t::binary:
  407. {
  408. binary = create<binary_t>();
  409. break;
  410. }
  411. case value_t::boolean:
  412. {
  413. boolean = static_cast<boolean_t>(false);
  414. break;
  415. }
  416. case value_t::number_integer:
  417. {
  418. number_integer = static_cast<number_integer_t>(0);
  419. break;
  420. }
  421. case value_t::number_unsigned:
  422. {
  423. number_unsigned = static_cast<number_unsigned_t>(0);
  424. break;
  425. }
  426. case value_t::number_float:
  427. {
  428. number_float = static_cast<number_float_t>(0.0);
  429. break;
  430. }
  431. case value_t::null:
  432. {
  433. object = nullptr; // silence warning, see #821
  434. break;
  435. }
  436. case value_t::discarded:
  437. default:
  438. {
  439. object = nullptr; // silence warning, see #821
  440. if (JSON_HEDLEY_UNLIKELY(t == value_t::null))
  441. {
  442. JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.11.2", nullptr)); // LCOV_EXCL_LINE
  443. }
  444. break;
  445. }
  446. }
  447. }
  448. /// constructor for strings
  449. json_value(const string_t& value) : string(create<string_t>(value)) {}
  450. /// constructor for rvalue strings
  451. json_value(string_t&& value) : string(create<string_t>(std::move(value))) {}
  452. /// constructor for objects
  453. json_value(const object_t& value) : object(create<object_t>(value)) {}
  454. /// constructor for rvalue objects
  455. json_value(object_t&& value) : object(create<object_t>(std::move(value))) {}
  456. /// constructor for arrays
  457. json_value(const array_t& value) : array(create<array_t>(value)) {}
  458. /// constructor for rvalue arrays
  459. json_value(array_t&& value) : array(create<array_t>(std::move(value))) {}
  460. /// constructor for binary arrays
  461. json_value(const typename binary_t::container_type& value) : binary(create<binary_t>(value)) {}
  462. /// constructor for rvalue binary arrays
  463. json_value(typename binary_t::container_type&& value) : binary(create<binary_t>(std::move(value))) {}
  464. /// constructor for binary arrays (internal type)
  465. json_value(const binary_t& value) : binary(create<binary_t>(value)) {}
  466. /// constructor for rvalue binary arrays (internal type)
  467. json_value(binary_t&& value) : binary(create<binary_t>(std::move(value))) {}
  468. void destroy(value_t t)
  469. {
  470. if (t == value_t::array || t == value_t::object)
  471. {
  472. // flatten the current json_value to a heap-allocated stack
  473. std::vector<basic_json> stack;
  474. // move the top-level items to stack
  475. if (t == value_t::array)
  476. {
  477. stack.reserve(array->size());
  478. std::move(array->begin(), array->end(), std::back_inserter(stack));
  479. }
  480. else
  481. {
  482. stack.reserve(object->size());
  483. for (auto&& it : *object)
  484. {
  485. stack.push_back(std::move(it.second));
  486. }
  487. }
  488. while (!stack.empty())
  489. {
  490. // move the last item to local variable to be processed
  491. basic_json current_item(std::move(stack.back()));
  492. stack.pop_back();
  493. // if current_item is array/object, move
  494. // its children to the stack to be processed later
  495. if (current_item.is_array())
  496. {
  497. std::move(current_item.m_value.array->begin(), current_item.m_value.array->end(), std::back_inserter(stack));
  498. current_item.m_value.array->clear();
  499. }
  500. else if (current_item.is_object())
  501. {
  502. for (auto&& it : *current_item.m_value.object)
  503. {
  504. stack.push_back(std::move(it.second));
  505. }
  506. current_item.m_value.object->clear();
  507. }
  508. // it's now safe that current_item get destructed
  509. // since it doesn't have any children
  510. }
  511. }
  512. switch (t)
  513. {
  514. case value_t::object:
  515. {
  516. AllocatorType<object_t> alloc;
  517. std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
  518. std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
  519. break;
  520. }
  521. case value_t::array:
  522. {
  523. AllocatorType<array_t> alloc;
  524. std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
  525. std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
  526. break;
  527. }
  528. case value_t::string:
  529. {
  530. AllocatorType<string_t> alloc;
  531. std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
  532. std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
  533. break;
  534. }
  535. case value_t::binary:
  536. {
  537. AllocatorType<binary_t> alloc;
  538. std::allocator_traits<decltype(alloc)>::destroy(alloc, binary);
  539. std::allocator_traits<decltype(alloc)>::deallocate(alloc, binary, 1);
  540. break;
  541. }
  542. case value_t::null:
  543. case value_t::boolean:
  544. case value_t::number_integer:
  545. case value_t::number_unsigned:
  546. case value_t::number_float:
  547. case value_t::discarded:
  548. default:
  549. {
  550. break;
  551. }
  552. }
  553. }
  554. };
  555. private:
  556. /*!
  557. @brief checks the class invariants
  558. This function asserts the class invariants. It needs to be called at the
  559. end of every constructor to make sure that created objects respect the
  560. invariant. Furthermore, it has to be called each time the type of a JSON
  561. value is changed, because the invariant expresses a relationship between
  562. @a m_type and @a m_value.
  563. Furthermore, the parent relation is checked for arrays and objects: If
  564. @a check_parents true and the value is an array or object, then the
  565. container's elements must have the current value as parent.
  566. @param[in] check_parents whether the parent relation should be checked.
  567. The value is true by default and should only be set to false
  568. during destruction of objects when the invariant does not
  569. need to hold.
  570. */
  571. void assert_invariant(bool check_parents = true) const noexcept
  572. {
  573. JSON_ASSERT(m_type != value_t::object || m_value.object != nullptr);
  574. JSON_ASSERT(m_type != value_t::array || m_value.array != nullptr);
  575. JSON_ASSERT(m_type != value_t::string || m_value.string != nullptr);
  576. JSON_ASSERT(m_type != value_t::binary || m_value.binary != nullptr);
  577. #if JSON_DIAGNOSTICS
  578. JSON_TRY
  579. {
  580. // cppcheck-suppress assertWithSideEffect
  581. JSON_ASSERT(!check_parents || !is_structured() || std::all_of(begin(), end(), [this](const basic_json & j)
  582. {
  583. return j.m_parent == this;
  584. }));
  585. }
  586. JSON_CATCH(...) {} // LCOV_EXCL_LINE
  587. #endif
  588. static_cast<void>(check_parents);
  589. }
  590. void set_parents()
  591. {
  592. #if JSON_DIAGNOSTICS
  593. switch (m_type)
  594. {
  595. case value_t::array:
  596. {
  597. for (auto& element : *m_value.array)
  598. {
  599. element.m_parent = this;
  600. }
  601. break;
  602. }
  603. case value_t::object:
  604. {
  605. for (auto& element : *m_value.object)
  606. {
  607. element.second.m_parent = this;
  608. }
  609. break;
  610. }
  611. case value_t::null:
  612. case value_t::string:
  613. case value_t::boolean:
  614. case value_t::number_integer:
  615. case value_t::number_unsigned:
  616. case value_t::number_float:
  617. case value_t::binary:
  618. case value_t::discarded:
  619. default:
  620. break;
  621. }
  622. #endif
  623. }
  624. iterator set_parents(iterator it, typename iterator::difference_type count_set_parents)
  625. {
  626. #if JSON_DIAGNOSTICS
  627. for (typename iterator::difference_type i = 0; i < count_set_parents; ++i)
  628. {
  629. (it + i)->m_parent = this;
  630. }
  631. #else
  632. static_cast<void>(count_set_parents);
  633. #endif
  634. return it;
  635. }
  636. reference set_parent(reference j, std::size_t old_capacity = static_cast<std::size_t>(-1))
  637. {
  638. #if JSON_DIAGNOSTICS
  639. if (old_capacity != static_cast<std::size_t>(-1))
  640. {
  641. // see https://github.com/nlohmann/json/issues/2838
  642. JSON_ASSERT(type() == value_t::array);
  643. if (JSON_HEDLEY_UNLIKELY(m_value.array->capacity() != old_capacity))
  644. {
  645. // capacity has changed: update all parents
  646. set_parents();
  647. return j;
  648. }
  649. }
  650. // ordered_json uses a vector internally, so pointers could have
  651. // been invalidated; see https://github.com/nlohmann/json/issues/2962
  652. #ifdef JSON_HEDLEY_MSVC_VERSION
  653. #pragma warning(push )
  654. #pragma warning(disable : 4127) // ignore warning to replace if with if constexpr
  655. #endif
  656. if (detail::is_ordered_map<object_t>::value)
  657. {
  658. set_parents();
  659. return j;
  660. }
  661. #ifdef JSON_HEDLEY_MSVC_VERSION
  662. #pragma warning( pop )
  663. #endif
  664. j.m_parent = this;
  665. #else
  666. static_cast<void>(j);
  667. static_cast<void>(old_capacity);
  668. #endif
  669. return j;
  670. }
  671. public:
  672. //////////////////////////
  673. // JSON parser callback //
  674. //////////////////////////
  675. /// @brief parser event types
  676. /// @sa https://json.nlohmann.me/api/basic_json/parse_event_t/
  677. using parse_event_t = detail::parse_event_t;
  678. /// @brief per-element parser callback type
  679. /// @sa https://json.nlohmann.me/api/basic_json/parser_callback_t/
  680. using parser_callback_t = detail::parser_callback_t<basic_json>;
  681. //////////////////
  682. // constructors //
  683. //////////////////
  684. /// @name constructors and destructors
  685. /// Constructors of class @ref basic_json, copy/move constructor, copy
  686. /// assignment, static functions creating objects, and the destructor.
  687. /// @{
  688. /// @brief create an empty value with a given type
  689. /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
  690. basic_json(const value_t v)
  691. : m_type(v), m_value(v)
  692. {
  693. assert_invariant();
  694. }
  695. /// @brief create a null object
  696. /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
  697. basic_json(std::nullptr_t = nullptr) noexcept // NOLINT(bugprone-exception-escape)
  698. : basic_json(value_t::null)
  699. {
  700. assert_invariant();
  701. }
  702. /// @brief create a JSON value from compatible types
  703. /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
  704. template < typename CompatibleType,
  705. typename U = detail::uncvref_t<CompatibleType>,
  706. detail::enable_if_t <
  707. !detail::is_basic_json<U>::value && detail::is_compatible_type<basic_json_t, U>::value, int > = 0 >
  708. basic_json(CompatibleType && val) noexcept(noexcept( // NOLINT(bugprone-forwarding-reference-overload,bugprone-exception-escape)
  709. JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
  710. std::forward<CompatibleType>(val))))
  711. {
  712. JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
  713. set_parents();
  714. assert_invariant();
  715. }
  716. /// @brief create a JSON value from an existing one
  717. /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
  718. template < typename BasicJsonType,
  719. detail::enable_if_t <
  720. detail::is_basic_json<BasicJsonType>::value&& !std::is_same<basic_json, BasicJsonType>::value, int > = 0 >
  721. basic_json(const BasicJsonType& val)
  722. {
  723. using other_boolean_t = typename BasicJsonType::boolean_t;
  724. using other_number_float_t = typename BasicJsonType::number_float_t;
  725. using other_number_integer_t = typename BasicJsonType::number_integer_t;
  726. using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  727. using other_string_t = typename BasicJsonType::string_t;
  728. using other_object_t = typename BasicJsonType::object_t;
  729. using other_array_t = typename BasicJsonType::array_t;
  730. using other_binary_t = typename BasicJsonType::binary_t;
  731. switch (val.type())
  732. {
  733. case value_t::boolean:
  734. JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>());
  735. break;
  736. case value_t::number_float:
  737. JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>());
  738. break;
  739. case value_t::number_integer:
  740. JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>());
  741. break;
  742. case value_t::number_unsigned:
  743. JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>());
  744. break;
  745. case value_t::string:
  746. JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>());
  747. break;
  748. case value_t::object:
  749. JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>());
  750. break;
  751. case value_t::array:
  752. JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>());
  753. break;
  754. case value_t::binary:
  755. JSONSerializer<other_binary_t>::to_json(*this, val.template get_ref<const other_binary_t&>());
  756. break;
  757. case value_t::null:
  758. *this = nullptr;
  759. break;
  760. case value_t::discarded:
  761. m_type = value_t::discarded;
  762. break;
  763. default: // LCOV_EXCL_LINE
  764. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  765. }
  766. JSON_ASSERT(m_type == val.type());
  767. set_parents();
  768. assert_invariant();
  769. }
  770. /// @brief create a container (array or object) from an initializer list
  771. /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
  772. basic_json(initializer_list_t init,
  773. bool type_deduction = true,
  774. value_t manual_type = value_t::array)
  775. {
  776. // check if each element is an array with two elements whose first
  777. // element is a string
  778. bool is_an_object = std::all_of(init.begin(), init.end(),
  779. [](const detail::json_ref<basic_json>& element_ref)
  780. {
  781. return element_ref->is_array() && element_ref->size() == 2 && (*element_ref)[0].is_string();
  782. });
  783. // adjust type if type deduction is not wanted
  784. if (!type_deduction)
  785. {
  786. // if array is wanted, do not create an object though possible
  787. if (manual_type == value_t::array)
  788. {
  789. is_an_object = false;
  790. }
  791. // if object is wanted but impossible, throw an exception
  792. if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object && !is_an_object))
  793. {
  794. JSON_THROW(type_error::create(301, "cannot create object from initializer list", nullptr));
  795. }
  796. }
  797. if (is_an_object)
  798. {
  799. // the initializer list is a list of pairs -> create object
  800. m_type = value_t::object;
  801. m_value = value_t::object;
  802. for (auto& element_ref : init)
  803. {
  804. auto element = element_ref.moved_or_copied();
  805. m_value.object->emplace(
  806. std::move(*((*element.m_value.array)[0].m_value.string)),
  807. std::move((*element.m_value.array)[1]));
  808. }
  809. }
  810. else
  811. {
  812. // the initializer list describes an array -> create array
  813. m_type = value_t::array;
  814. m_value.array = create<array_t>(init.begin(), init.end());
  815. }
  816. set_parents();
  817. assert_invariant();
  818. }
  819. /// @brief explicitly create a binary array (without subtype)
  820. /// @sa https://json.nlohmann.me/api/basic_json/binary/
  821. JSON_HEDLEY_WARN_UNUSED_RESULT
  822. static basic_json binary(const typename binary_t::container_type& init)
  823. {
  824. auto res = basic_json();
  825. res.m_type = value_t::binary;
  826. res.m_value = init;
  827. return res;
  828. }
  829. /// @brief explicitly create a binary array (with subtype)
  830. /// @sa https://json.nlohmann.me/api/basic_json/binary/
  831. JSON_HEDLEY_WARN_UNUSED_RESULT
  832. static basic_json binary(const typename binary_t::container_type& init, typename binary_t::subtype_type subtype)
  833. {
  834. auto res = basic_json();
  835. res.m_type = value_t::binary;
  836. res.m_value = binary_t(init, subtype);
  837. return res;
  838. }
  839. /// @brief explicitly create a binary array
  840. /// @sa https://json.nlohmann.me/api/basic_json/binary/
  841. JSON_HEDLEY_WARN_UNUSED_RESULT
  842. static basic_json binary(typename binary_t::container_type&& init)
  843. {
  844. auto res = basic_json();
  845. res.m_type = value_t::binary;
  846. res.m_value = std::move(init);
  847. return res;
  848. }
  849. /// @brief explicitly create a binary array (with subtype)
  850. /// @sa https://json.nlohmann.me/api/basic_json/binary/
  851. JSON_HEDLEY_WARN_UNUSED_RESULT
  852. static basic_json binary(typename binary_t::container_type&& init, typename binary_t::subtype_type subtype)
  853. {
  854. auto res = basic_json();
  855. res.m_type = value_t::binary;
  856. res.m_value = binary_t(std::move(init), subtype);
  857. return res;
  858. }
  859. /// @brief explicitly create an array from an initializer list
  860. /// @sa https://json.nlohmann.me/api/basic_json/array/
  861. JSON_HEDLEY_WARN_UNUSED_RESULT
  862. static basic_json array(initializer_list_t init = {})
  863. {
  864. return basic_json(init, false, value_t::array);
  865. }
  866. /// @brief explicitly create an object from an initializer list
  867. /// @sa https://json.nlohmann.me/api/basic_json/object/
  868. JSON_HEDLEY_WARN_UNUSED_RESULT
  869. static basic_json object(initializer_list_t init = {})
  870. {
  871. return basic_json(init, false, value_t::object);
  872. }
  873. /// @brief construct an array with count copies of given value
  874. /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
  875. basic_json(size_type cnt, const basic_json& val)
  876. : m_type(value_t::array)
  877. {
  878. m_value.array = create<array_t>(cnt, val);
  879. set_parents();
  880. assert_invariant();
  881. }
  882. /// @brief construct a JSON container given an iterator range
  883. /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
  884. template < class InputIT, typename std::enable_if <
  885. std::is_same<InputIT, typename basic_json_t::iterator>::value ||
  886. std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int >::type = 0 >
  887. basic_json(InputIT first, InputIT last)
  888. {
  889. JSON_ASSERT(first.m_object != nullptr);
  890. JSON_ASSERT(last.m_object != nullptr);
  891. // make sure iterator fits the current value
  892. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  893. {
  894. JSON_THROW(invalid_iterator::create(201, "iterators are not compatible", nullptr));
  895. }
  896. // copy type from first iterator
  897. m_type = first.m_object->m_type;
  898. // check if iterator range is complete for primitive values
  899. switch (m_type)
  900. {
  901. case value_t::boolean:
  902. case value_t::number_float:
  903. case value_t::number_integer:
  904. case value_t::number_unsigned:
  905. case value_t::string:
  906. {
  907. if (JSON_HEDLEY_UNLIKELY(!first.m_it.primitive_iterator.is_begin()
  908. || !last.m_it.primitive_iterator.is_end()))
  909. {
  910. JSON_THROW(invalid_iterator::create(204, "iterators out of range", first.m_object));
  911. }
  912. break;
  913. }
  914. case value_t::null:
  915. case value_t::object:
  916. case value_t::array:
  917. case value_t::binary:
  918. case value_t::discarded:
  919. default:
  920. break;
  921. }
  922. switch (m_type)
  923. {
  924. case value_t::number_integer:
  925. {
  926. m_value.number_integer = first.m_object->m_value.number_integer;
  927. break;
  928. }
  929. case value_t::number_unsigned:
  930. {
  931. m_value.number_unsigned = first.m_object->m_value.number_unsigned;
  932. break;
  933. }
  934. case value_t::number_float:
  935. {
  936. m_value.number_float = first.m_object->m_value.number_float;
  937. break;
  938. }
  939. case value_t::boolean:
  940. {
  941. m_value.boolean = first.m_object->m_value.boolean;
  942. break;
  943. }
  944. case value_t::string:
  945. {
  946. m_value = *first.m_object->m_value.string;
  947. break;
  948. }
  949. case value_t::object:
  950. {
  951. m_value.object = create<object_t>(first.m_it.object_iterator,
  952. last.m_it.object_iterator);
  953. break;
  954. }
  955. case value_t::array:
  956. {
  957. m_value.array = create<array_t>(first.m_it.array_iterator,
  958. last.m_it.array_iterator);
  959. break;
  960. }
  961. case value_t::binary:
  962. {
  963. m_value = *first.m_object->m_value.binary;
  964. break;
  965. }
  966. case value_t::null:
  967. case value_t::discarded:
  968. default:
  969. JSON_THROW(invalid_iterator::create(206, detail::concat("cannot construct with iterators from ", first.m_object->type_name()), first.m_object));
  970. }
  971. set_parents();
  972. assert_invariant();
  973. }
  974. ///////////////////////////////////////
  975. // other constructors and destructor //
  976. ///////////////////////////////////////
  977. template<typename JsonRef,
  978. detail::enable_if_t<detail::conjunction<detail::is_json_ref<JsonRef>,
  979. std::is_same<typename JsonRef::value_type, basic_json>>::value, int> = 0 >
  980. basic_json(const JsonRef& ref) : basic_json(ref.moved_or_copied()) {}
  981. /// @brief copy constructor
  982. /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
  983. basic_json(const basic_json& other)
  984. : json_base_class_t(other),
  985. m_type(other.m_type)
  986. {
  987. // check of passed value is valid
  988. other.assert_invariant();
  989. switch (m_type)
  990. {
  991. case value_t::object:
  992. {
  993. m_value = *other.m_value.object;
  994. break;
  995. }
  996. case value_t::array:
  997. {
  998. m_value = *other.m_value.array;
  999. break;
  1000. }
  1001. case value_t::string:
  1002. {
  1003. m_value = *other.m_value.string;
  1004. break;
  1005. }
  1006. case value_t::boolean:
  1007. {
  1008. m_value = other.m_value.boolean;
  1009. break;
  1010. }
  1011. case value_t::number_integer:
  1012. {
  1013. m_value = other.m_value.number_integer;
  1014. break;
  1015. }
  1016. case value_t::number_unsigned:
  1017. {
  1018. m_value = other.m_value.number_unsigned;
  1019. break;
  1020. }
  1021. case value_t::number_float:
  1022. {
  1023. m_value = other.m_value.number_float;
  1024. break;
  1025. }
  1026. case value_t::binary:
  1027. {
  1028. m_value = *other.m_value.binary;
  1029. break;
  1030. }
  1031. case value_t::null:
  1032. case value_t::discarded:
  1033. default:
  1034. break;
  1035. }
  1036. set_parents();
  1037. assert_invariant();
  1038. }
  1039. /// @brief move constructor
  1040. /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
  1041. basic_json(basic_json&& other) noexcept
  1042. : json_base_class_t(std::move(other)),
  1043. m_type(std::move(other.m_type)),
  1044. m_value(std::move(other.m_value))
  1045. {
  1046. // check that passed value is valid
  1047. other.assert_invariant(false); // NOLINT(bugprone-use-after-move,hicpp-invalid-access-moved)
  1048. // invalidate payload
  1049. other.m_type = value_t::null;
  1050. other.m_value = {};
  1051. set_parents();
  1052. assert_invariant();
  1053. }
  1054. /// @brief copy assignment
  1055. /// @sa https://json.nlohmann.me/api/basic_json/operator=/
  1056. basic_json& operator=(basic_json other) noexcept (
  1057. std::is_nothrow_move_constructible<value_t>::value&&
  1058. std::is_nothrow_move_assignable<value_t>::value&&
  1059. std::is_nothrow_move_constructible<json_value>::value&&
  1060. std::is_nothrow_move_assignable<json_value>::value&&
  1061. std::is_nothrow_move_assignable<json_base_class_t>::value
  1062. )
  1063. {
  1064. // check that passed value is valid
  1065. other.assert_invariant();
  1066. using std::swap;
  1067. swap(m_type, other.m_type);
  1068. swap(m_value, other.m_value);
  1069. json_base_class_t::operator=(std::move(other));
  1070. set_parents();
  1071. assert_invariant();
  1072. return *this;
  1073. }
  1074. /// @brief destructor
  1075. /// @sa https://json.nlohmann.me/api/basic_json/~basic_json/
  1076. ~basic_json() noexcept
  1077. {
  1078. assert_invariant(false);
  1079. m_value.destroy(m_type);
  1080. }
  1081. /// @}
  1082. public:
  1083. ///////////////////////
  1084. // object inspection //
  1085. ///////////////////////
  1086. /// @name object inspection
  1087. /// Functions to inspect the type of a JSON value.
  1088. /// @{
  1089. /// @brief serialization
  1090. /// @sa https://json.nlohmann.me/api/basic_json/dump/
  1091. string_t dump(const int indent = -1,
  1092. const char indent_char = ' ',
  1093. const bool ensure_ascii = false,
  1094. const error_handler_t error_handler = error_handler_t::strict) const
  1095. {
  1096. string_t result;
  1097. serializer s(detail::output_adapter<char, string_t>(result), indent_char, error_handler);
  1098. if (indent >= 0)
  1099. {
  1100. s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
  1101. }
  1102. else
  1103. {
  1104. s.dump(*this, false, ensure_ascii, 0);
  1105. }
  1106. return result;
  1107. }
  1108. /// @brief return the type of the JSON value (explicit)
  1109. /// @sa https://json.nlohmann.me/api/basic_json/type/
  1110. constexpr value_t type() const noexcept
  1111. {
  1112. return m_type;
  1113. }
  1114. /// @brief return whether type is primitive
  1115. /// @sa https://json.nlohmann.me/api/basic_json/is_primitive/
  1116. constexpr bool is_primitive() const noexcept
  1117. {
  1118. return is_null() || is_string() || is_boolean() || is_number() || is_binary();
  1119. }
  1120. /// @brief return whether type is structured
  1121. /// @sa https://json.nlohmann.me/api/basic_json/is_structured/
  1122. constexpr bool is_structured() const noexcept
  1123. {
  1124. return is_array() || is_object();
  1125. }
  1126. /// @brief return whether value is null
  1127. /// @sa https://json.nlohmann.me/api/basic_json/is_null/
  1128. constexpr bool is_null() const noexcept
  1129. {
  1130. return m_type == value_t::null;
  1131. }
  1132. /// @brief return whether value is a boolean
  1133. /// @sa https://json.nlohmann.me/api/basic_json/is_boolean/
  1134. constexpr bool is_boolean() const noexcept
  1135. {
  1136. return m_type == value_t::boolean;
  1137. }
  1138. /// @brief return whether value is a number
  1139. /// @sa https://json.nlohmann.me/api/basic_json/is_number/
  1140. constexpr bool is_number() const noexcept
  1141. {
  1142. return is_number_integer() || is_number_float();
  1143. }
  1144. /// @brief return whether value is an integer number
  1145. /// @sa https://json.nlohmann.me/api/basic_json/is_number_integer/
  1146. constexpr bool is_number_integer() const noexcept
  1147. {
  1148. return m_type == value_t::number_integer || m_type == value_t::number_unsigned;
  1149. }
  1150. /// @brief return whether value is an unsigned integer number
  1151. /// @sa https://json.nlohmann.me/api/basic_json/is_number_unsigned/
  1152. constexpr bool is_number_unsigned() const noexcept
  1153. {
  1154. return m_type == value_t::number_unsigned;
  1155. }
  1156. /// @brief return whether value is a floating-point number
  1157. /// @sa https://json.nlohmann.me/api/basic_json/is_number_float/
  1158. constexpr bool is_number_float() const noexcept
  1159. {
  1160. return m_type == value_t::number_float;
  1161. }
  1162. /// @brief return whether value is an object
  1163. /// @sa https://json.nlohmann.me/api/basic_json/is_object/
  1164. constexpr bool is_object() const noexcept
  1165. {
  1166. return m_type == value_t::object;
  1167. }
  1168. /// @brief return whether value is an array
  1169. /// @sa https://json.nlohmann.me/api/basic_json/is_array/
  1170. constexpr bool is_array() const noexcept
  1171. {
  1172. return m_type == value_t::array;
  1173. }
  1174. /// @brief return whether value is a string
  1175. /// @sa https://json.nlohmann.me/api/basic_json/is_string/
  1176. constexpr bool is_string() const noexcept
  1177. {
  1178. return m_type == value_t::string;
  1179. }
  1180. /// @brief return whether value is a binary array
  1181. /// @sa https://json.nlohmann.me/api/basic_json/is_binary/
  1182. constexpr bool is_binary() const noexcept
  1183. {
  1184. return m_type == value_t::binary;
  1185. }
  1186. /// @brief return whether value is discarded
  1187. /// @sa https://json.nlohmann.me/api/basic_json/is_discarded/
  1188. constexpr bool is_discarded() const noexcept
  1189. {
  1190. return m_type == value_t::discarded;
  1191. }
  1192. /// @brief return the type of the JSON value (implicit)
  1193. /// @sa https://json.nlohmann.me/api/basic_json/operator_value_t/
  1194. constexpr operator value_t() const noexcept
  1195. {
  1196. return m_type;
  1197. }
  1198. /// @}
  1199. private:
  1200. //////////////////
  1201. // value access //
  1202. //////////////////
  1203. /// get a boolean (explicit)
  1204. boolean_t get_impl(boolean_t* /*unused*/) const
  1205. {
  1206. if (JSON_HEDLEY_LIKELY(is_boolean()))
  1207. {
  1208. return m_value.boolean;
  1209. }
  1210. JSON_THROW(type_error::create(302, detail::concat("type must be boolean, but is ", type_name()), this));
  1211. }
  1212. /// get a pointer to the value (object)
  1213. object_t* get_impl_ptr(object_t* /*unused*/) noexcept
  1214. {
  1215. return is_object() ? m_value.object : nullptr;
  1216. }
  1217. /// get a pointer to the value (object)
  1218. constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
  1219. {
  1220. return is_object() ? m_value.object : nullptr;
  1221. }
  1222. /// get a pointer to the value (array)
  1223. array_t* get_impl_ptr(array_t* /*unused*/) noexcept
  1224. {
  1225. return is_array() ? m_value.array : nullptr;
  1226. }
  1227. /// get a pointer to the value (array)
  1228. constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
  1229. {
  1230. return is_array() ? m_value.array : nullptr;
  1231. }
  1232. /// get a pointer to the value (string)
  1233. string_t* get_impl_ptr(string_t* /*unused*/) noexcept
  1234. {
  1235. return is_string() ? m_value.string : nullptr;
  1236. }
  1237. /// get a pointer to the value (string)
  1238. constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
  1239. {
  1240. return is_string() ? m_value.string : nullptr;
  1241. }
  1242. /// get a pointer to the value (boolean)
  1243. boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
  1244. {
  1245. return is_boolean() ? &m_value.boolean : nullptr;
  1246. }
  1247. /// get a pointer to the value (boolean)
  1248. constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
  1249. {
  1250. return is_boolean() ? &m_value.boolean : nullptr;
  1251. }
  1252. /// get a pointer to the value (integer number)
  1253. number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
  1254. {
  1255. return is_number_integer() ? &m_value.number_integer : nullptr;
  1256. }
  1257. /// get a pointer to the value (integer number)
  1258. constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
  1259. {
  1260. return is_number_integer() ? &m_value.number_integer : nullptr;
  1261. }
  1262. /// get a pointer to the value (unsigned number)
  1263. number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
  1264. {
  1265. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  1266. }
  1267. /// get a pointer to the value (unsigned number)
  1268. constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
  1269. {
  1270. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  1271. }
  1272. /// get a pointer to the value (floating-point number)
  1273. number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
  1274. {
  1275. return is_number_float() ? &m_value.number_float : nullptr;
  1276. }
  1277. /// get a pointer to the value (floating-point number)
  1278. constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
  1279. {
  1280. return is_number_float() ? &m_value.number_float : nullptr;
  1281. }
  1282. /// get a pointer to the value (binary)
  1283. binary_t* get_impl_ptr(binary_t* /*unused*/) noexcept
  1284. {
  1285. return is_binary() ? m_value.binary : nullptr;
  1286. }
  1287. /// get a pointer to the value (binary)
  1288. constexpr const binary_t* get_impl_ptr(const binary_t* /*unused*/) const noexcept
  1289. {
  1290. return is_binary() ? m_value.binary : nullptr;
  1291. }
  1292. /*!
  1293. @brief helper function to implement get_ref()
  1294. This function helps to implement get_ref() without code duplication for
  1295. const and non-const overloads
  1296. @tparam ThisType will be deduced as `basic_json` or `const basic_json`
  1297. @throw type_error.303 if ReferenceType does not match underlying value
  1298. type of the current JSON
  1299. */
  1300. template<typename ReferenceType, typename ThisType>
  1301. static ReferenceType get_ref_impl(ThisType& obj)
  1302. {
  1303. // delegate the call to get_ptr<>()
  1304. auto* ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
  1305. if (JSON_HEDLEY_LIKELY(ptr != nullptr))
  1306. {
  1307. return *ptr;
  1308. }
  1309. JSON_THROW(type_error::create(303, detail::concat("incompatible ReferenceType for get_ref, actual type is ", obj.type_name()), &obj));
  1310. }
  1311. public:
  1312. /// @name value access
  1313. /// Direct access to the stored value of a JSON value.
  1314. /// @{
  1315. /// @brief get a pointer value (implicit)
  1316. /// @sa https://json.nlohmann.me/api/basic_json/get_ptr/
  1317. template<typename PointerType, typename std::enable_if<
  1318. std::is_pointer<PointerType>::value, int>::type = 0>
  1319. auto get_ptr() noexcept -> decltype(std::declval<basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  1320. {
  1321. // delegate the call to get_impl_ptr<>()
  1322. return get_impl_ptr(static_cast<PointerType>(nullptr));
  1323. }
  1324. /// @brief get a pointer value (implicit)
  1325. /// @sa https://json.nlohmann.me/api/basic_json/get_ptr/
  1326. template < typename PointerType, typename std::enable_if <
  1327. std::is_pointer<PointerType>::value&&
  1328. std::is_const<typename std::remove_pointer<PointerType>::type>::value, int >::type = 0 >
  1329. constexpr auto get_ptr() const noexcept -> decltype(std::declval<const basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  1330. {
  1331. // delegate the call to get_impl_ptr<>() const
  1332. return get_impl_ptr(static_cast<PointerType>(nullptr));
  1333. }
  1334. private:
  1335. /*!
  1336. @brief get a value (explicit)
  1337. Explicit type conversion between the JSON value and a compatible value
  1338. which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  1339. and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  1340. The value is converted by calling the @ref json_serializer<ValueType>
  1341. `from_json()` method.
  1342. The function is equivalent to executing
  1343. @code {.cpp}
  1344. ValueType ret;
  1345. JSONSerializer<ValueType>::from_json(*this, ret);
  1346. return ret;
  1347. @endcode
  1348. This overloads is chosen if:
  1349. - @a ValueType is not @ref basic_json,
  1350. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  1351. `void from_json(const basic_json&, ValueType&)`, and
  1352. - @ref json_serializer<ValueType> does not have a `from_json()` method of
  1353. the form `ValueType from_json(const basic_json&)`
  1354. @tparam ValueType the returned value type
  1355. @return copy of the JSON value, converted to @a ValueType
  1356. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  1357. @liveexample{The example below shows several conversions from JSON values
  1358. to other types. There a few things to note: (1) Floating-point numbers can
  1359. be converted to integers\, (2) A JSON array can be converted to a standard
  1360. `std::vector<short>`\, (3) A JSON object can be converted to C++
  1361. associative containers such as `std::unordered_map<std::string\,
  1362. json>`.,get__ValueType_const}
  1363. @since version 2.1.0
  1364. */
  1365. template < typename ValueType,
  1366. detail::enable_if_t <
  1367. detail::is_default_constructible<ValueType>::value&&
  1368. detail::has_from_json<basic_json_t, ValueType>::value,
  1369. int > = 0 >
  1370. ValueType get_impl(detail::priority_tag<0> /*unused*/) const noexcept(noexcept(
  1371. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
  1372. {
  1373. auto ret = ValueType();
  1374. JSONSerializer<ValueType>::from_json(*this, ret);
  1375. return ret;
  1376. }
  1377. /*!
  1378. @brief get a value (explicit); special case
  1379. Explicit type conversion between the JSON value and a compatible value
  1380. which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  1381. and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  1382. The value is converted by calling the @ref json_serializer<ValueType>
  1383. `from_json()` method.
  1384. The function is equivalent to executing
  1385. @code {.cpp}
  1386. return JSONSerializer<ValueType>::from_json(*this);
  1387. @endcode
  1388. This overloads is chosen if:
  1389. - @a ValueType is not @ref basic_json and
  1390. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  1391. `ValueType from_json(const basic_json&)`
  1392. @note If @ref json_serializer<ValueType> has both overloads of
  1393. `from_json()`, this one is chosen.
  1394. @tparam ValueType the returned value type
  1395. @return copy of the JSON value, converted to @a ValueType
  1396. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  1397. @since version 2.1.0
  1398. */
  1399. template < typename ValueType,
  1400. detail::enable_if_t <
  1401. detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  1402. int > = 0 >
  1403. ValueType get_impl(detail::priority_tag<1> /*unused*/) const noexcept(noexcept(
  1404. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>())))
  1405. {
  1406. return JSONSerializer<ValueType>::from_json(*this);
  1407. }
  1408. /*!
  1409. @brief get special-case overload
  1410. This overloads converts the current @ref basic_json in a different
  1411. @ref basic_json type
  1412. @tparam BasicJsonType == @ref basic_json
  1413. @return a copy of *this, converted into @a BasicJsonType
  1414. @complexity Depending on the implementation of the called `from_json()`
  1415. method.
  1416. @since version 3.2.0
  1417. */
  1418. template < typename BasicJsonType,
  1419. detail::enable_if_t <
  1420. detail::is_basic_json<BasicJsonType>::value,
  1421. int > = 0 >
  1422. BasicJsonType get_impl(detail::priority_tag<2> /*unused*/) const
  1423. {
  1424. return *this;
  1425. }
  1426. /*!
  1427. @brief get special-case overload
  1428. This overloads avoids a lot of template boilerplate, it can be seen as the
  1429. identity method
  1430. @tparam BasicJsonType == @ref basic_json
  1431. @return a copy of *this
  1432. @complexity Constant.
  1433. @since version 2.1.0
  1434. */
  1435. template<typename BasicJsonType,
  1436. detail::enable_if_t<
  1437. std::is_same<BasicJsonType, basic_json_t>::value,
  1438. int> = 0>
  1439. basic_json get_impl(detail::priority_tag<3> /*unused*/) const
  1440. {
  1441. return *this;
  1442. }
  1443. /*!
  1444. @brief get a pointer value (explicit)
  1445. @copydoc get()
  1446. */
  1447. template<typename PointerType,
  1448. detail::enable_if_t<
  1449. std::is_pointer<PointerType>::value,
  1450. int> = 0>
  1451. constexpr auto get_impl(detail::priority_tag<4> /*unused*/) const noexcept
  1452. -> decltype(std::declval<const basic_json_t&>().template get_ptr<PointerType>())
  1453. {
  1454. // delegate the call to get_ptr
  1455. return get_ptr<PointerType>();
  1456. }
  1457. public:
  1458. /*!
  1459. @brief get a (pointer) value (explicit)
  1460. Performs explicit type conversion between the JSON value and a compatible value if required.
  1461. - If the requested type is a pointer to the internally stored JSON value that pointer is returned.
  1462. No copies are made.
  1463. - If the requested type is the current @ref basic_json, or a different @ref basic_json convertible
  1464. from the current @ref basic_json.
  1465. - Otherwise the value is converted by calling the @ref json_serializer<ValueType> `from_json()`
  1466. method.
  1467. @tparam ValueTypeCV the provided value type
  1468. @tparam ValueType the returned value type
  1469. @return copy of the JSON value, converted to @tparam ValueType if necessary
  1470. @throw what @ref json_serializer<ValueType> `from_json()` method throws if conversion is required
  1471. @since version 2.1.0
  1472. */
  1473. template < typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>>
  1474. #if defined(JSON_HAS_CPP_14)
  1475. constexpr
  1476. #endif
  1477. auto get() const noexcept(
  1478. noexcept(std::declval<const basic_json_t&>().template get_impl<ValueType>(detail::priority_tag<4> {})))
  1479. -> decltype(std::declval<const basic_json_t&>().template get_impl<ValueType>(detail::priority_tag<4> {}))
  1480. {
  1481. // we cannot static_assert on ValueTypeCV being non-const, because
  1482. // there is support for get<const basic_json_t>(), which is why we
  1483. // still need the uncvref
  1484. static_assert(!std::is_reference<ValueTypeCV>::value,
  1485. "get() cannot be used with reference types, you might want to use get_ref()");
  1486. return get_impl<ValueType>(detail::priority_tag<4> {});
  1487. }
  1488. /*!
  1489. @brief get a pointer value (explicit)
  1490. Explicit pointer access to the internally stored JSON value. No copies are
  1491. made.
  1492. @warning The pointer becomes invalid if the underlying JSON object
  1493. changes.
  1494. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  1495. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  1496. @ref number_unsigned_t, or @ref number_float_t.
  1497. @return pointer to the internally stored JSON value if the requested
  1498. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  1499. @complexity Constant.
  1500. @liveexample{The example below shows how pointers to internal values of a
  1501. JSON value can be requested. Note that no type conversions are made and a
  1502. `nullptr` is returned if the value and the requested pointer type does not
  1503. match.,get__PointerType}
  1504. @sa see @ref get_ptr() for explicit pointer-member access
  1505. @since version 1.0.0
  1506. */
  1507. template<typename PointerType, typename std::enable_if<
  1508. std::is_pointer<PointerType>::value, int>::type = 0>
  1509. auto get() noexcept -> decltype(std::declval<basic_json_t&>().template get_ptr<PointerType>())
  1510. {
  1511. // delegate the call to get_ptr
  1512. return get_ptr<PointerType>();
  1513. }
  1514. /// @brief get a value (explicit)
  1515. /// @sa https://json.nlohmann.me/api/basic_json/get_to/
  1516. template < typename ValueType,
  1517. detail::enable_if_t <
  1518. !detail::is_basic_json<ValueType>::value&&
  1519. detail::has_from_json<basic_json_t, ValueType>::value,
  1520. int > = 0 >
  1521. ValueType & get_to(ValueType& v) const noexcept(noexcept(
  1522. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v)))
  1523. {
  1524. JSONSerializer<ValueType>::from_json(*this, v);
  1525. return v;
  1526. }
  1527. // specialization to allow calling get_to with a basic_json value
  1528. // see https://github.com/nlohmann/json/issues/2175
  1529. template<typename ValueType,
  1530. detail::enable_if_t <
  1531. detail::is_basic_json<ValueType>::value,
  1532. int> = 0>
  1533. ValueType & get_to(ValueType& v) const
  1534. {
  1535. v = *this;
  1536. return v;
  1537. }
  1538. template <
  1539. typename T, std::size_t N,
  1540. typename Array = T (&)[N], // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  1541. detail::enable_if_t <
  1542. detail::has_from_json<basic_json_t, Array>::value, int > = 0 >
  1543. Array get_to(T (&v)[N]) const // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  1544. noexcept(noexcept(JSONSerializer<Array>::from_json(
  1545. std::declval<const basic_json_t&>(), v)))
  1546. {
  1547. JSONSerializer<Array>::from_json(*this, v);
  1548. return v;
  1549. }
  1550. /// @brief get a reference value (implicit)
  1551. /// @sa https://json.nlohmann.me/api/basic_json/get_ref/
  1552. template<typename ReferenceType, typename std::enable_if<
  1553. std::is_reference<ReferenceType>::value, int>::type = 0>
  1554. ReferenceType get_ref()
  1555. {
  1556. // delegate call to get_ref_impl
  1557. return get_ref_impl<ReferenceType>(*this);
  1558. }
  1559. /// @brief get a reference value (implicit)
  1560. /// @sa https://json.nlohmann.me/api/basic_json/get_ref/
  1561. template < typename ReferenceType, typename std::enable_if <
  1562. std::is_reference<ReferenceType>::value&&
  1563. std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int >::type = 0 >
  1564. ReferenceType get_ref() const
  1565. {
  1566. // delegate call to get_ref_impl
  1567. return get_ref_impl<ReferenceType>(*this);
  1568. }
  1569. /*!
  1570. @brief get a value (implicit)
  1571. Implicit type conversion between the JSON value and a compatible value.
  1572. The call is realized by calling @ref get() const.
  1573. @tparam ValueType non-pointer type compatible to the JSON value, for
  1574. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  1575. `std::vector` types for JSON arrays. The character type of @ref string_t
  1576. as well as an initializer list of this type is excluded to avoid
  1577. ambiguities as these types implicitly convert to `std::string`.
  1578. @return copy of the JSON value, converted to type @a ValueType
  1579. @throw type_error.302 in case passed type @a ValueType is incompatible
  1580. to the JSON value type (e.g., the JSON value is of type boolean, but a
  1581. string is requested); see example below
  1582. @complexity Linear in the size of the JSON value.
  1583. @liveexample{The example below shows several conversions from JSON values
  1584. to other types. There a few things to note: (1) Floating-point numbers can
  1585. be converted to integers\, (2) A JSON array can be converted to a standard
  1586. `std::vector<short>`\, (3) A JSON object can be converted to C++
  1587. associative containers such as `std::unordered_map<std::string\,
  1588. json>`.,operator__ValueType}
  1589. @since version 1.0.0
  1590. */
  1591. template < typename ValueType, typename std::enable_if <
  1592. detail::conjunction <
  1593. detail::negation<std::is_pointer<ValueType>>,
  1594. detail::negation<std::is_same<ValueType, std::nullptr_t>>,
  1595. detail::negation<std::is_same<ValueType, detail::json_ref<basic_json>>>,
  1596. detail::negation<std::is_same<ValueType, typename string_t::value_type>>,
  1597. detail::negation<detail::is_basic_json<ValueType>>,
  1598. detail::negation<std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>>,
  1599. #if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) && _MSC_VER >= 1910 && _MSC_VER <= 1914))
  1600. detail::negation<std::is_same<ValueType, std::string_view>>,
  1601. #endif
  1602. #if defined(JSON_HAS_CPP_17)
  1603. detail::negation<std::is_same<ValueType, std::any>>,
  1604. #endif
  1605. detail::is_detected_lazy<detail::get_template_function, const basic_json_t&, ValueType>
  1606. >::value, int >::type = 0 >
  1607. JSON_EXPLICIT operator ValueType() const
  1608. {
  1609. // delegate the call to get<>() const
  1610. return get<ValueType>();
  1611. }
  1612. /// @brief get a binary value
  1613. /// @sa https://json.nlohmann.me/api/basic_json/get_binary/
  1614. binary_t& get_binary()
  1615. {
  1616. if (!is_binary())
  1617. {
  1618. JSON_THROW(type_error::create(302, detail::concat("type must be binary, but is ", type_name()), this));
  1619. }
  1620. return *get_ptr<binary_t*>();
  1621. }
  1622. /// @brief get a binary value
  1623. /// @sa https://json.nlohmann.me/api/basic_json/get_binary/
  1624. const binary_t& get_binary() const
  1625. {
  1626. if (!is_binary())
  1627. {
  1628. JSON_THROW(type_error::create(302, detail::concat("type must be binary, but is ", type_name()), this));
  1629. }
  1630. return *get_ptr<const binary_t*>();
  1631. }
  1632. /// @}
  1633. ////////////////////
  1634. // element access //
  1635. ////////////////////
  1636. /// @name element access
  1637. /// Access to the JSON value.
  1638. /// @{
  1639. /// @brief access specified array element with bounds checking
  1640. /// @sa https://json.nlohmann.me/api/basic_json/at/
  1641. reference at(size_type idx)
  1642. {
  1643. // at only works for arrays
  1644. if (JSON_HEDLEY_LIKELY(is_array()))
  1645. {
  1646. JSON_TRY
  1647. {
  1648. return set_parent(m_value.array->at(idx));
  1649. }
  1650. JSON_CATCH (std::out_of_range&)
  1651. {
  1652. // create better exception explanation
  1653. JSON_THROW(out_of_range::create(401, detail::concat("array index ", std::to_string(idx), " is out of range"), this));
  1654. }
  1655. }
  1656. else
  1657. {
  1658. JSON_THROW(type_error::create(304, detail::concat("cannot use at() with ", type_name()), this));
  1659. }
  1660. }
  1661. /// @brief access specified array element with bounds checking
  1662. /// @sa https://json.nlohmann.me/api/basic_json/at/
  1663. const_reference at(size_type idx) const
  1664. {
  1665. // at only works for arrays
  1666. if (JSON_HEDLEY_LIKELY(is_array()))
  1667. {
  1668. JSON_TRY
  1669. {
  1670. return m_value.array->at(idx);
  1671. }
  1672. JSON_CATCH (std::out_of_range&)
  1673. {
  1674. // create better exception explanation
  1675. JSON_THROW(out_of_range::create(401, detail::concat("array index ", std::to_string(idx), " is out of range"), this));
  1676. }
  1677. }
  1678. else
  1679. {
  1680. JSON_THROW(type_error::create(304, detail::concat("cannot use at() with ", type_name()), this));
  1681. }
  1682. }
  1683. /// @brief access specified object element with bounds checking
  1684. /// @sa https://json.nlohmann.me/api/basic_json/at/
  1685. reference at(const typename object_t::key_type& key)
  1686. {
  1687. // at only works for objects
  1688. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  1689. {
  1690. JSON_THROW(type_error::create(304, detail::concat("cannot use at() with ", type_name()), this));
  1691. }
  1692. auto it = m_value.object->find(key);
  1693. if (it == m_value.object->end())
  1694. {
  1695. JSON_THROW(out_of_range::create(403, detail::concat("key '", key, "' not found"), this));
  1696. }
  1697. return set_parent(it->second);
  1698. }
  1699. /// @brief access specified object element with bounds checking
  1700. /// @sa https://json.nlohmann.me/api/basic_json/at/
  1701. template<class KeyType, detail::enable_if_t<
  1702. detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0>
  1703. reference at(KeyType && key)
  1704. {
  1705. // at only works for objects
  1706. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  1707. {
  1708. JSON_THROW(type_error::create(304, detail::concat("cannot use at() with ", type_name()), this));
  1709. }
  1710. auto it = m_value.object->find(std::forward<KeyType>(key));
  1711. if (it == m_value.object->end())
  1712. {
  1713. JSON_THROW(out_of_range::create(403, detail::concat("key '", string_t(std::forward<KeyType>(key)), "' not found"), this));
  1714. }
  1715. return set_parent(it->second);
  1716. }
  1717. /// @brief access specified object element with bounds checking
  1718. /// @sa https://json.nlohmann.me/api/basic_json/at/
  1719. const_reference at(const typename object_t::key_type& key) const
  1720. {
  1721. // at only works for objects
  1722. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  1723. {
  1724. JSON_THROW(type_error::create(304, detail::concat("cannot use at() with ", type_name()), this));
  1725. }
  1726. auto it = m_value.object->find(key);
  1727. if (it == m_value.object->end())
  1728. {
  1729. JSON_THROW(out_of_range::create(403, detail::concat("key '", key, "' not found"), this));
  1730. }
  1731. return it->second;
  1732. }
  1733. /// @brief access specified object element with bounds checking
  1734. /// @sa https://json.nlohmann.me/api/basic_json/at/
  1735. template<class KeyType, detail::enable_if_t<
  1736. detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0>
  1737. const_reference at(KeyType && key) const
  1738. {
  1739. // at only works for objects
  1740. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  1741. {
  1742. JSON_THROW(type_error::create(304, detail::concat("cannot use at() with ", type_name()), this));
  1743. }
  1744. auto it = m_value.object->find(std::forward<KeyType>(key));
  1745. if (it == m_value.object->end())
  1746. {
  1747. JSON_THROW(out_of_range::create(403, detail::concat("key '", string_t(std::forward<KeyType>(key)), "' not found"), this));
  1748. }
  1749. return it->second;
  1750. }
  1751. /// @brief access specified array element
  1752. /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
  1753. reference operator[](size_type idx)
  1754. {
  1755. // implicitly convert null value to an empty array
  1756. if (is_null())
  1757. {
  1758. m_type = value_t::array;
  1759. m_value.array = create<array_t>();
  1760. assert_invariant();
  1761. }
  1762. // operator[] only works for arrays
  1763. if (JSON_HEDLEY_LIKELY(is_array()))
  1764. {
  1765. // fill up array with null values if given idx is outside range
  1766. if (idx >= m_value.array->size())
  1767. {
  1768. #if JSON_DIAGNOSTICS
  1769. // remember array size & capacity before resizing
  1770. const auto old_size = m_value.array->size();
  1771. const auto old_capacity = m_value.array->capacity();
  1772. #endif
  1773. m_value.array->resize(idx + 1);
  1774. #if JSON_DIAGNOSTICS
  1775. if (JSON_HEDLEY_UNLIKELY(m_value.array->capacity() != old_capacity))
  1776. {
  1777. // capacity has changed: update all parents
  1778. set_parents();
  1779. }
  1780. else
  1781. {
  1782. // set parent for values added above
  1783. set_parents(begin() + static_cast<typename iterator::difference_type>(old_size), static_cast<typename iterator::difference_type>(idx + 1 - old_size));
  1784. }
  1785. #endif
  1786. assert_invariant();
  1787. }
  1788. return m_value.array->operator[](idx);
  1789. }
  1790. JSON_THROW(type_error::create(305, detail::concat("cannot use operator[] with a numeric argument with ", type_name()), this));
  1791. }
  1792. /// @brief access specified array element
  1793. /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
  1794. const_reference operator[](size_type idx) const
  1795. {
  1796. // const operator[] only works for arrays
  1797. if (JSON_HEDLEY_LIKELY(is_array()))
  1798. {
  1799. return m_value.array->operator[](idx);
  1800. }
  1801. JSON_THROW(type_error::create(305, detail::concat("cannot use operator[] with a numeric argument with ", type_name()), this));
  1802. }
  1803. /// @brief access specified object element
  1804. /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
  1805. reference operator[](typename object_t::key_type key)
  1806. {
  1807. // implicitly convert null value to an empty object
  1808. if (is_null())
  1809. {
  1810. m_type = value_t::object;
  1811. m_value.object = create<object_t>();
  1812. assert_invariant();
  1813. }
  1814. // operator[] only works for objects
  1815. if (JSON_HEDLEY_LIKELY(is_object()))
  1816. {
  1817. auto result = m_value.object->emplace(std::move(key), nullptr);
  1818. return set_parent(result.first->second);
  1819. }
  1820. JSON_THROW(type_error::create(305, detail::concat("cannot use operator[] with a string argument with ", type_name()), this));
  1821. }
  1822. /// @brief access specified object element
  1823. /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
  1824. const_reference operator[](const typename object_t::key_type& key) const
  1825. {
  1826. // const operator[] only works for objects
  1827. if (JSON_HEDLEY_LIKELY(is_object()))
  1828. {
  1829. auto it = m_value.object->find(key);
  1830. JSON_ASSERT(it != m_value.object->end());
  1831. return it->second;
  1832. }
  1833. JSON_THROW(type_error::create(305, detail::concat("cannot use operator[] with a string argument with ", type_name()), this));
  1834. }
  1835. // these two functions resolve a (const) char * ambiguity affecting Clang and MSVC
  1836. // (they seemingly cannot be constrained to resolve the ambiguity)
  1837. template<typename T>
  1838. reference operator[](T* key)
  1839. {
  1840. return operator[](typename object_t::key_type(key));
  1841. }
  1842. template<typename T>
  1843. const_reference operator[](T* key) const
  1844. {
  1845. return operator[](typename object_t::key_type(key));
  1846. }
  1847. /// @brief access specified object element
  1848. /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
  1849. template<class KeyType, detail::enable_if_t<
  1850. detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int > = 0 >
  1851. reference operator[](KeyType && key)
  1852. {
  1853. // implicitly convert null value to an empty object
  1854. if (is_null())
  1855. {
  1856. m_type = value_t::object;
  1857. m_value.object = create<object_t>();
  1858. assert_invariant();
  1859. }
  1860. // operator[] only works for objects
  1861. if (JSON_HEDLEY_LIKELY(is_object()))
  1862. {
  1863. auto result = m_value.object->emplace(std::forward<KeyType>(key), nullptr);
  1864. return set_parent(result.first->second);
  1865. }
  1866. JSON_THROW(type_error::create(305, detail::concat("cannot use operator[] with a string argument with ", type_name()), this));
  1867. }
  1868. /// @brief access specified object element
  1869. /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
  1870. template<class KeyType, detail::enable_if_t<
  1871. detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int > = 0 >
  1872. const_reference operator[](KeyType && key) const
  1873. {
  1874. // const operator[] only works for objects
  1875. if (JSON_HEDLEY_LIKELY(is_object()))
  1876. {
  1877. auto it = m_value.object->find(std::forward<KeyType>(key));
  1878. JSON_ASSERT(it != m_value.object->end());
  1879. return it->second;
  1880. }
  1881. JSON_THROW(type_error::create(305, detail::concat("cannot use operator[] with a string argument with ", type_name()), this));
  1882. }
  1883. private:
  1884. template<typename KeyType>
  1885. using is_comparable_with_object_key = detail::is_comparable <
  1886. object_comparator_t, const typename object_t::key_type&, KeyType >;
  1887. template<typename ValueType>
  1888. using value_return_type = std::conditional <
  1889. detail::is_c_string_uncvref<ValueType>::value,
  1890. string_t, typename std::decay<ValueType>::type >;
  1891. public:
  1892. /// @brief access specified object element with default value
  1893. /// @sa https://json.nlohmann.me/api/basic_json/value/
  1894. template < class ValueType, detail::enable_if_t <
  1895. !detail::is_transparent<object_comparator_t>::value
  1896. && detail::is_getable<basic_json_t, ValueType>::value
  1897. && !std::is_same<value_t, detail::uncvref_t<ValueType>>::value, int > = 0 >
  1898. ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
  1899. {
  1900. // value only works for objects
  1901. if (JSON_HEDLEY_LIKELY(is_object()))
  1902. {
  1903. // if key is found, return value and given default value otherwise
  1904. const auto it = find(key);
  1905. if (it != end())
  1906. {
  1907. return it->template get<ValueType>();
  1908. }
  1909. return default_value;
  1910. }
  1911. JSON_THROW(type_error::create(306, detail::concat("cannot use value() with ", type_name()), this));
  1912. }
  1913. /// @brief access specified object element with default value
  1914. /// @sa https://json.nlohmann.me/api/basic_json/value/
  1915. template < class ValueType, class ReturnType = typename value_return_type<ValueType>::type,
  1916. detail::enable_if_t <
  1917. !detail::is_transparent<object_comparator_t>::value
  1918. && detail::is_getable<basic_json_t, ReturnType>::value
  1919. && !std::is_same<value_t, detail::uncvref_t<ValueType>>::value, int > = 0 >
  1920. ReturnType value(const typename object_t::key_type& key, ValueType && default_value) const
  1921. {
  1922. // value only works for objects
  1923. if (JSON_HEDLEY_LIKELY(is_object()))
  1924. {
  1925. // if key is found, return value and given default value otherwise
  1926. const auto it = find(key);
  1927. if (it != end())
  1928. {
  1929. return it->template get<ReturnType>();
  1930. }
  1931. return std::forward<ValueType>(default_value);
  1932. }
  1933. JSON_THROW(type_error::create(306, detail::concat("cannot use value() with ", type_name()), this));
  1934. }
  1935. /// @brief access specified object element with default value
  1936. /// @sa https://json.nlohmann.me/api/basic_json/value/
  1937. template < class ValueType, class KeyType, detail::enable_if_t <
  1938. detail::is_transparent<object_comparator_t>::value
  1939. && !detail::is_json_pointer<KeyType>::value
  1940. && is_comparable_with_object_key<KeyType>::value
  1941. && detail::is_getable<basic_json_t, ValueType>::value
  1942. && !std::is_same<value_t, detail::uncvref_t<ValueType>>::value, int > = 0 >
  1943. ValueType value(KeyType && key, const ValueType& default_value) const
  1944. {
  1945. // value only works for objects
  1946. if (JSON_HEDLEY_LIKELY(is_object()))
  1947. {
  1948. // if key is found, return value and given default value otherwise
  1949. const auto it = find(std::forward<KeyType>(key));
  1950. if (it != end())
  1951. {
  1952. return it->template get<ValueType>();
  1953. }
  1954. return default_value;
  1955. }
  1956. JSON_THROW(type_error::create(306, detail::concat("cannot use value() with ", type_name()), this));
  1957. }
  1958. /// @brief access specified object element via JSON Pointer with default value
  1959. /// @sa https://json.nlohmann.me/api/basic_json/value/
  1960. template < class ValueType, class KeyType, class ReturnType = typename value_return_type<ValueType>::type,
  1961. detail::enable_if_t <
  1962. detail::is_transparent<object_comparator_t>::value
  1963. && !detail::is_json_pointer<KeyType>::value
  1964. && is_comparable_with_object_key<KeyType>::value
  1965. && detail::is_getable<basic_json_t, ReturnType>::value
  1966. && !std::is_same<value_t, detail::uncvref_t<ValueType>>::value, int > = 0 >
  1967. ReturnType value(KeyType && key, ValueType && default_value) const
  1968. {
  1969. // value only works for objects
  1970. if (JSON_HEDLEY_LIKELY(is_object()))
  1971. {
  1972. // if key is found, return value and given default value otherwise
  1973. const auto it = find(std::forward<KeyType>(key));
  1974. if (it != end())
  1975. {
  1976. return it->template get<ReturnType>();
  1977. }
  1978. return std::forward<ValueType>(default_value);
  1979. }
  1980. JSON_THROW(type_error::create(306, detail::concat("cannot use value() with ", type_name()), this));
  1981. }
  1982. /// @brief access specified object element via JSON Pointer with default value
  1983. /// @sa https://json.nlohmann.me/api/basic_json/value/
  1984. template < class ValueType, detail::enable_if_t <
  1985. detail::is_getable<basic_json_t, ValueType>::value
  1986. && !std::is_same<value_t, detail::uncvref_t<ValueType>>::value, int > = 0 >
  1987. ValueType value(const json_pointer& ptr, const ValueType& default_value) const
  1988. {
  1989. // value only works for objects
  1990. if (JSON_HEDLEY_LIKELY(is_object()))
  1991. {
  1992. // if pointer resolves a value, return it or use default value
  1993. JSON_TRY
  1994. {
  1995. return ptr.get_checked(this).template get<ValueType>();
  1996. }
  1997. JSON_INTERNAL_CATCH (out_of_range&)
  1998. {
  1999. return default_value;
  2000. }
  2001. }
  2002. JSON_THROW(type_error::create(306, detail::concat("cannot use value() with ", type_name()), this));
  2003. }
  2004. /// @brief access specified object element via JSON Pointer with default value
  2005. /// @sa https://json.nlohmann.me/api/basic_json/value/
  2006. template < class ValueType, class ReturnType = typename value_return_type<ValueType>::type,
  2007. detail::enable_if_t <
  2008. detail::is_getable<basic_json_t, ReturnType>::value
  2009. && !std::is_same<value_t, detail::uncvref_t<ValueType>>::value, int > = 0 >
  2010. ReturnType value(const json_pointer& ptr, ValueType && default_value) const
  2011. {
  2012. // value only works for objects
  2013. if (JSON_HEDLEY_LIKELY(is_object()))
  2014. {
  2015. // if pointer resolves a value, return it or use default value
  2016. JSON_TRY
  2017. {
  2018. return ptr.get_checked(this).template get<ReturnType>();
  2019. }
  2020. JSON_INTERNAL_CATCH (out_of_range&)
  2021. {
  2022. return std::forward<ValueType>(default_value);
  2023. }
  2024. }
  2025. JSON_THROW(type_error::create(306, detail::concat("cannot use value() with ", type_name()), this));
  2026. }
  2027. template < class ValueType, class BasicJsonType, detail::enable_if_t <
  2028. detail::is_basic_json<BasicJsonType>::value
  2029. && detail::is_getable<basic_json_t, ValueType>::value
  2030. && !std::is_same<value_t, detail::uncvref_t<ValueType>>::value, int > = 0 >
  2031. JSON_HEDLEY_DEPRECATED_FOR(3.11.0, basic_json::json_pointer or nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens)
  2032. ValueType value(const ::nlohmann::json_pointer<BasicJsonType>& ptr, const ValueType& default_value) const
  2033. {
  2034. return value(ptr.convert(), default_value);
  2035. }
  2036. template < class ValueType, class BasicJsonType, class ReturnType = typename value_return_type<ValueType>::type,
  2037. detail::enable_if_t <
  2038. detail::is_basic_json<BasicJsonType>::value
  2039. && detail::is_getable<basic_json_t, ReturnType>::value
  2040. && !std::is_same<value_t, detail::uncvref_t<ValueType>>::value, int > = 0 >
  2041. JSON_HEDLEY_DEPRECATED_FOR(3.11.0, basic_json::json_pointer or nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens)
  2042. ReturnType value(const ::nlohmann::json_pointer<BasicJsonType>& ptr, ValueType && default_value) const
  2043. {
  2044. return value(ptr.convert(), std::forward<ValueType>(default_value));
  2045. }
  2046. /// @brief access the first element
  2047. /// @sa https://json.nlohmann.me/api/basic_json/front/
  2048. reference front()
  2049. {
  2050. return *begin();
  2051. }
  2052. /// @brief access the first element
  2053. /// @sa https://json.nlohmann.me/api/basic_json/front/
  2054. const_reference front() const
  2055. {
  2056. return *cbegin();
  2057. }
  2058. /// @brief access the last element
  2059. /// @sa https://json.nlohmann.me/api/basic_json/back/
  2060. reference back()
  2061. {
  2062. auto tmp = end();
  2063. --tmp;
  2064. return *tmp;
  2065. }
  2066. /// @brief access the last element
  2067. /// @sa https://json.nlohmann.me/api/basic_json/back/
  2068. const_reference back() const
  2069. {
  2070. auto tmp = cend();
  2071. --tmp;
  2072. return *tmp;
  2073. }
  2074. /// @brief remove element given an iterator
  2075. /// @sa https://json.nlohmann.me/api/basic_json/erase/
  2076. template < class IteratorType, detail::enable_if_t <
  2077. std::is_same<IteratorType, typename basic_json_t::iterator>::value ||
  2078. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int > = 0 >
  2079. IteratorType erase(IteratorType pos)
  2080. {
  2081. // make sure iterator fits the current value
  2082. if (JSON_HEDLEY_UNLIKELY(this != pos.m_object))
  2083. {
  2084. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", this));
  2085. }
  2086. IteratorType result = end();
  2087. switch (m_type)
  2088. {
  2089. case value_t::boolean:
  2090. case value_t::number_float:
  2091. case value_t::number_integer:
  2092. case value_t::number_unsigned:
  2093. case value_t::string:
  2094. case value_t::binary:
  2095. {
  2096. if (JSON_HEDLEY_UNLIKELY(!pos.m_it.primitive_iterator.is_begin()))
  2097. {
  2098. JSON_THROW(invalid_iterator::create(205, "iterator out of range", this));
  2099. }
  2100. if (is_string())
  2101. {
  2102. AllocatorType<string_t> alloc;
  2103. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  2104. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  2105. m_value.string = nullptr;
  2106. }
  2107. else if (is_binary())
  2108. {
  2109. AllocatorType<binary_t> alloc;
  2110. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.binary);
  2111. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.binary, 1);
  2112. m_value.binary = nullptr;
  2113. }
  2114. m_type = value_t::null;
  2115. assert_invariant();
  2116. break;
  2117. }
  2118. case value_t::object:
  2119. {
  2120. result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
  2121. break;
  2122. }
  2123. case value_t::array:
  2124. {
  2125. result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
  2126. break;
  2127. }
  2128. case value_t::null:
  2129. case value_t::discarded:
  2130. default:
  2131. JSON_THROW(type_error::create(307, detail::concat("cannot use erase() with ", type_name()), this));
  2132. }
  2133. return result;
  2134. }
  2135. /// @brief remove elements given an iterator range
  2136. /// @sa https://json.nlohmann.me/api/basic_json/erase/
  2137. template < class IteratorType, detail::enable_if_t <
  2138. std::is_same<IteratorType, typename basic_json_t::iterator>::value ||
  2139. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int > = 0 >
  2140. IteratorType erase(IteratorType first, IteratorType last)
  2141. {
  2142. // make sure iterator fits the current value
  2143. if (JSON_HEDLEY_UNLIKELY(this != first.m_object || this != last.m_object))
  2144. {
  2145. JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value", this));
  2146. }
  2147. IteratorType result = end();
  2148. switch (m_type)
  2149. {
  2150. case value_t::boolean:
  2151. case value_t::number_float:
  2152. case value_t::number_integer:
  2153. case value_t::number_unsigned:
  2154. case value_t::string:
  2155. case value_t::binary:
  2156. {
  2157. if (JSON_HEDLEY_LIKELY(!first.m_it.primitive_iterator.is_begin()
  2158. || !last.m_it.primitive_iterator.is_end()))
  2159. {
  2160. JSON_THROW(invalid_iterator::create(204, "iterators out of range", this));
  2161. }
  2162. if (is_string())
  2163. {
  2164. AllocatorType<string_t> alloc;
  2165. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  2166. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  2167. m_value.string = nullptr;
  2168. }
  2169. else if (is_binary())
  2170. {
  2171. AllocatorType<binary_t> alloc;
  2172. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.binary);
  2173. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.binary, 1);
  2174. m_value.binary = nullptr;
  2175. }
  2176. m_type = value_t::null;
  2177. assert_invariant();
  2178. break;
  2179. }
  2180. case value_t::object:
  2181. {
  2182. result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
  2183. last.m_it.object_iterator);
  2184. break;
  2185. }
  2186. case value_t::array:
  2187. {
  2188. result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
  2189. last.m_it.array_iterator);
  2190. break;
  2191. }
  2192. case value_t::null:
  2193. case value_t::discarded:
  2194. default:
  2195. JSON_THROW(type_error::create(307, detail::concat("cannot use erase() with ", type_name()), this));
  2196. }
  2197. return result;
  2198. }
  2199. private:
  2200. template < typename KeyType, detail::enable_if_t <
  2201. detail::has_erase_with_key_type<basic_json_t, KeyType>::value, int > = 0 >
  2202. size_type erase_internal(KeyType && key)
  2203. {
  2204. // this erase only works for objects
  2205. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  2206. {
  2207. JSON_THROW(type_error::create(307, detail::concat("cannot use erase() with ", type_name()), this));
  2208. }
  2209. return m_value.object->erase(std::forward<KeyType>(key));
  2210. }
  2211. template < typename KeyType, detail::enable_if_t <
  2212. !detail::has_erase_with_key_type<basic_json_t, KeyType>::value, int > = 0 >
  2213. size_type erase_internal(KeyType && key)
  2214. {
  2215. // this erase only works for objects
  2216. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  2217. {
  2218. JSON_THROW(type_error::create(307, detail::concat("cannot use erase() with ", type_name()), this));
  2219. }
  2220. const auto it = m_value.object->find(std::forward<KeyType>(key));
  2221. if (it != m_value.object->end())
  2222. {
  2223. m_value.object->erase(it);
  2224. return 1;
  2225. }
  2226. return 0;
  2227. }
  2228. public:
  2229. /// @brief remove element from a JSON object given a key
  2230. /// @sa https://json.nlohmann.me/api/basic_json/erase/
  2231. size_type erase(const typename object_t::key_type& key)
  2232. {
  2233. // the indirection via erase_internal() is added to avoid making this
  2234. // function a template and thus de-rank it during overload resolution
  2235. return erase_internal(key);
  2236. }
  2237. /// @brief remove element from a JSON object given a key
  2238. /// @sa https://json.nlohmann.me/api/basic_json/erase/
  2239. template<class KeyType, detail::enable_if_t<
  2240. detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0>
  2241. size_type erase(KeyType && key)
  2242. {
  2243. return erase_internal(std::forward<KeyType>(key));
  2244. }
  2245. /// @brief remove element from a JSON array given an index
  2246. /// @sa https://json.nlohmann.me/api/basic_json/erase/
  2247. void erase(const size_type idx)
  2248. {
  2249. // this erase only works for arrays
  2250. if (JSON_HEDLEY_LIKELY(is_array()))
  2251. {
  2252. if (JSON_HEDLEY_UNLIKELY(idx >= size()))
  2253. {
  2254. JSON_THROW(out_of_range::create(401, detail::concat("array index ", std::to_string(idx), " is out of range"), this));
  2255. }
  2256. m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
  2257. }
  2258. else
  2259. {
  2260. JSON_THROW(type_error::create(307, detail::concat("cannot use erase() with ", type_name()), this));
  2261. }
  2262. }
  2263. /// @}
  2264. ////////////
  2265. // lookup //
  2266. ////////////
  2267. /// @name lookup
  2268. /// @{
  2269. /// @brief find an element in a JSON object
  2270. /// @sa https://json.nlohmann.me/api/basic_json/find/
  2271. iterator find(const typename object_t::key_type& key)
  2272. {
  2273. auto result = end();
  2274. if (is_object())
  2275. {
  2276. result.m_it.object_iterator = m_value.object->find(key);
  2277. }
  2278. return result;
  2279. }
  2280. /// @brief find an element in a JSON object
  2281. /// @sa https://json.nlohmann.me/api/basic_json/find/
  2282. const_iterator find(const typename object_t::key_type& key) const
  2283. {
  2284. auto result = cend();
  2285. if (is_object())
  2286. {
  2287. result.m_it.object_iterator = m_value.object->find(key);
  2288. }
  2289. return result;
  2290. }
  2291. /// @brief find an element in a JSON object
  2292. /// @sa https://json.nlohmann.me/api/basic_json/find/
  2293. template<class KeyType, detail::enable_if_t<
  2294. detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0>
  2295. iterator find(KeyType && key)
  2296. {
  2297. auto result = end();
  2298. if (is_object())
  2299. {
  2300. result.m_it.object_iterator = m_value.object->find(std::forward<KeyType>(key));
  2301. }
  2302. return result;
  2303. }
  2304. /// @brief find an element in a JSON object
  2305. /// @sa https://json.nlohmann.me/api/basic_json/find/
  2306. template<class KeyType, detail::enable_if_t<
  2307. detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0>
  2308. const_iterator find(KeyType && key) const
  2309. {
  2310. auto result = cend();
  2311. if (is_object())
  2312. {
  2313. result.m_it.object_iterator = m_value.object->find(std::forward<KeyType>(key));
  2314. }
  2315. return result;
  2316. }
  2317. /// @brief returns the number of occurrences of a key in a JSON object
  2318. /// @sa https://json.nlohmann.me/api/basic_json/count/
  2319. size_type count(const typename object_t::key_type& key) const
  2320. {
  2321. // return 0 for all nonobject types
  2322. return is_object() ? m_value.object->count(key) : 0;
  2323. }
  2324. /// @brief returns the number of occurrences of a key in a JSON object
  2325. /// @sa https://json.nlohmann.me/api/basic_json/count/
  2326. template<class KeyType, detail::enable_if_t<
  2327. detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0>
  2328. size_type count(KeyType && key) const
  2329. {
  2330. // return 0 for all nonobject types
  2331. return is_object() ? m_value.object->count(std::forward<KeyType>(key)) : 0;
  2332. }
  2333. /// @brief check the existence of an element in a JSON object
  2334. /// @sa https://json.nlohmann.me/api/basic_json/contains/
  2335. bool contains(const typename object_t::key_type& key) const
  2336. {
  2337. return is_object() && m_value.object->find(key) != m_value.object->end();
  2338. }
  2339. /// @brief check the existence of an element in a JSON object
  2340. /// @sa https://json.nlohmann.me/api/basic_json/contains/
  2341. template<class KeyType, detail::enable_if_t<
  2342. detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0>
  2343. bool contains(KeyType && key) const
  2344. {
  2345. return is_object() && m_value.object->find(std::forward<KeyType>(key)) != m_value.object->end();
  2346. }
  2347. /// @brief check the existence of an element in a JSON object given a JSON pointer
  2348. /// @sa https://json.nlohmann.me/api/basic_json/contains/
  2349. bool contains(const json_pointer& ptr) const
  2350. {
  2351. return ptr.contains(this);
  2352. }
  2353. template<typename BasicJsonType, detail::enable_if_t<detail::is_basic_json<BasicJsonType>::value, int> = 0>
  2354. JSON_HEDLEY_DEPRECATED_FOR(3.11.0, basic_json::json_pointer or nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens)
  2355. bool contains(const typename ::nlohmann::json_pointer<BasicJsonType>& ptr) const
  2356. {
  2357. return ptr.contains(this);
  2358. }
  2359. /// @}
  2360. ///////////////
  2361. // iterators //
  2362. ///////////////
  2363. /// @name iterators
  2364. /// @{
  2365. /// @brief returns an iterator to the first element
  2366. /// @sa https://json.nlohmann.me/api/basic_json/begin/
  2367. iterator begin() noexcept
  2368. {
  2369. iterator result(this);
  2370. result.set_begin();
  2371. return result;
  2372. }
  2373. /// @brief returns an iterator to the first element
  2374. /// @sa https://json.nlohmann.me/api/basic_json/begin/
  2375. const_iterator begin() const noexcept
  2376. {
  2377. return cbegin();
  2378. }
  2379. /// @brief returns a const iterator to the first element
  2380. /// @sa https://json.nlohmann.me/api/basic_json/cbegin/
  2381. const_iterator cbegin() const noexcept
  2382. {
  2383. const_iterator result(this);
  2384. result.set_begin();
  2385. return result;
  2386. }
  2387. /// @brief returns an iterator to one past the last element
  2388. /// @sa https://json.nlohmann.me/api/basic_json/end/
  2389. iterator end() noexcept
  2390. {
  2391. iterator result(this);
  2392. result.set_end();
  2393. return result;
  2394. }
  2395. /// @brief returns an iterator to one past the last element
  2396. /// @sa https://json.nlohmann.me/api/basic_json/end/
  2397. const_iterator end() const noexcept
  2398. {
  2399. return cend();
  2400. }
  2401. /// @brief returns an iterator to one past the last element
  2402. /// @sa https://json.nlohmann.me/api/basic_json/cend/
  2403. const_iterator cend() const noexcept
  2404. {
  2405. const_iterator result(this);
  2406. result.set_end();
  2407. return result;
  2408. }
  2409. /// @brief returns an iterator to the reverse-beginning
  2410. /// @sa https://json.nlohmann.me/api/basic_json/rbegin/
  2411. reverse_iterator rbegin() noexcept
  2412. {
  2413. return reverse_iterator(end());
  2414. }
  2415. /// @brief returns an iterator to the reverse-beginning
  2416. /// @sa https://json.nlohmann.me/api/basic_json/rbegin/
  2417. const_reverse_iterator rbegin() const noexcept
  2418. {
  2419. return crbegin();
  2420. }
  2421. /// @brief returns an iterator to the reverse-end
  2422. /// @sa https://json.nlohmann.me/api/basic_json/rend/
  2423. reverse_iterator rend() noexcept
  2424. {
  2425. return reverse_iterator(begin());
  2426. }
  2427. /// @brief returns an iterator to the reverse-end
  2428. /// @sa https://json.nlohmann.me/api/basic_json/rend/
  2429. const_reverse_iterator rend() const noexcept
  2430. {
  2431. return crend();
  2432. }
  2433. /// @brief returns a const reverse iterator to the last element
  2434. /// @sa https://json.nlohmann.me/api/basic_json/crbegin/
  2435. const_reverse_iterator crbegin() const noexcept
  2436. {
  2437. return const_reverse_iterator(cend());
  2438. }
  2439. /// @brief returns a const reverse iterator to one before the first
  2440. /// @sa https://json.nlohmann.me/api/basic_json/crend/
  2441. const_reverse_iterator crend() const noexcept
  2442. {
  2443. return const_reverse_iterator(cbegin());
  2444. }
  2445. public:
  2446. /// @brief wrapper to access iterator member functions in range-based for
  2447. /// @sa https://json.nlohmann.me/api/basic_json/items/
  2448. /// @deprecated This function is deprecated since 3.1.0 and will be removed in
  2449. /// version 4.0.0 of the library. Please use @ref items() instead;
  2450. /// that is, replace `json::iterator_wrapper(j)` with `j.items()`.
  2451. JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items())
  2452. static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept
  2453. {
  2454. return ref.items();
  2455. }
  2456. /// @brief wrapper to access iterator member functions in range-based for
  2457. /// @sa https://json.nlohmann.me/api/basic_json/items/
  2458. /// @deprecated This function is deprecated since 3.1.0 and will be removed in
  2459. /// version 4.0.0 of the library. Please use @ref items() instead;
  2460. /// that is, replace `json::iterator_wrapper(j)` with `j.items()`.
  2461. JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items())
  2462. static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept
  2463. {
  2464. return ref.items();
  2465. }
  2466. /// @brief helper to access iterator member functions in range-based for
  2467. /// @sa https://json.nlohmann.me/api/basic_json/items/
  2468. iteration_proxy<iterator> items() noexcept
  2469. {
  2470. return iteration_proxy<iterator>(*this);
  2471. }
  2472. /// @brief helper to access iterator member functions in range-based for
  2473. /// @sa https://json.nlohmann.me/api/basic_json/items/
  2474. iteration_proxy<const_iterator> items() const noexcept
  2475. {
  2476. return iteration_proxy<const_iterator>(*this);
  2477. }
  2478. /// @}
  2479. //////////////
  2480. // capacity //
  2481. //////////////
  2482. /// @name capacity
  2483. /// @{
  2484. /// @brief checks whether the container is empty.
  2485. /// @sa https://json.nlohmann.me/api/basic_json/empty/
  2486. bool empty() const noexcept
  2487. {
  2488. switch (m_type)
  2489. {
  2490. case value_t::null:
  2491. {
  2492. // null values are empty
  2493. return true;
  2494. }
  2495. case value_t::array:
  2496. {
  2497. // delegate call to array_t::empty()
  2498. return m_value.array->empty();
  2499. }
  2500. case value_t::object:
  2501. {
  2502. // delegate call to object_t::empty()
  2503. return m_value.object->empty();
  2504. }
  2505. case value_t::string:
  2506. case value_t::boolean:
  2507. case value_t::number_integer:
  2508. case value_t::number_unsigned:
  2509. case value_t::number_float:
  2510. case value_t::binary:
  2511. case value_t::discarded:
  2512. default:
  2513. {
  2514. // all other types are nonempty
  2515. return false;
  2516. }
  2517. }
  2518. }
  2519. /// @brief returns the number of elements
  2520. /// @sa https://json.nlohmann.me/api/basic_json/size/
  2521. size_type size() const noexcept
  2522. {
  2523. switch (m_type)
  2524. {
  2525. case value_t::null:
  2526. {
  2527. // null values are empty
  2528. return 0;
  2529. }
  2530. case value_t::array:
  2531. {
  2532. // delegate call to array_t::size()
  2533. return m_value.array->size();
  2534. }
  2535. case value_t::object:
  2536. {
  2537. // delegate call to object_t::size()
  2538. return m_value.object->size();
  2539. }
  2540. case value_t::string:
  2541. case value_t::boolean:
  2542. case value_t::number_integer:
  2543. case value_t::number_unsigned:
  2544. case value_t::number_float:
  2545. case value_t::binary:
  2546. case value_t::discarded:
  2547. default:
  2548. {
  2549. // all other types have size 1
  2550. return 1;
  2551. }
  2552. }
  2553. }
  2554. /// @brief returns the maximum possible number of elements
  2555. /// @sa https://json.nlohmann.me/api/basic_json/max_size/
  2556. size_type max_size() const noexcept
  2557. {
  2558. switch (m_type)
  2559. {
  2560. case value_t::array:
  2561. {
  2562. // delegate call to array_t::max_size()
  2563. return m_value.array->max_size();
  2564. }
  2565. case value_t::object:
  2566. {
  2567. // delegate call to object_t::max_size()
  2568. return m_value.object->max_size();
  2569. }
  2570. case value_t::null:
  2571. case value_t::string:
  2572. case value_t::boolean:
  2573. case value_t::number_integer:
  2574. case value_t::number_unsigned:
  2575. case value_t::number_float:
  2576. case value_t::binary:
  2577. case value_t::discarded:
  2578. default:
  2579. {
  2580. // all other types have max_size() == size()
  2581. return size();
  2582. }
  2583. }
  2584. }
  2585. /// @}
  2586. ///////////////
  2587. // modifiers //
  2588. ///////////////
  2589. /// @name modifiers
  2590. /// @{
  2591. /// @brief clears the contents
  2592. /// @sa https://json.nlohmann.me/api/basic_json/clear/
  2593. void clear() noexcept
  2594. {
  2595. switch (m_type)
  2596. {
  2597. case value_t::number_integer:
  2598. {
  2599. m_value.number_integer = 0;
  2600. break;
  2601. }
  2602. case value_t::number_unsigned:
  2603. {
  2604. m_value.number_unsigned = 0;
  2605. break;
  2606. }
  2607. case value_t::number_float:
  2608. {
  2609. m_value.number_float = 0.0;
  2610. break;
  2611. }
  2612. case value_t::boolean:
  2613. {
  2614. m_value.boolean = false;
  2615. break;
  2616. }
  2617. case value_t::string:
  2618. {
  2619. m_value.string->clear();
  2620. break;
  2621. }
  2622. case value_t::binary:
  2623. {
  2624. m_value.binary->clear();
  2625. break;
  2626. }
  2627. case value_t::array:
  2628. {
  2629. m_value.array->clear();
  2630. break;
  2631. }
  2632. case value_t::object:
  2633. {
  2634. m_value.object->clear();
  2635. break;
  2636. }
  2637. case value_t::null:
  2638. case value_t::discarded:
  2639. default:
  2640. break;
  2641. }
  2642. }
  2643. /// @brief add an object to an array
  2644. /// @sa https://json.nlohmann.me/api/basic_json/push_back/
  2645. void push_back(basic_json&& val)
  2646. {
  2647. // push_back only works for null objects or arrays
  2648. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array())))
  2649. {
  2650. JSON_THROW(type_error::create(308, detail::concat("cannot use push_back() with ", type_name()), this));
  2651. }
  2652. // transform null object into an array
  2653. if (is_null())
  2654. {
  2655. m_type = value_t::array;
  2656. m_value = value_t::array;
  2657. assert_invariant();
  2658. }
  2659. // add element to array (move semantics)
  2660. const auto old_capacity = m_value.array->capacity();
  2661. m_value.array->push_back(std::move(val));
  2662. set_parent(m_value.array->back(), old_capacity);
  2663. // if val is moved from, basic_json move constructor marks it null, so we do not call the destructor
  2664. }
  2665. /// @brief add an object to an array
  2666. /// @sa https://json.nlohmann.me/api/basic_json/operator+=/
  2667. reference operator+=(basic_json&& val)
  2668. {
  2669. push_back(std::move(val));
  2670. return *this;
  2671. }
  2672. /// @brief add an object to an array
  2673. /// @sa https://json.nlohmann.me/api/basic_json/push_back/
  2674. void push_back(const basic_json& val)
  2675. {
  2676. // push_back only works for null objects or arrays
  2677. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array())))
  2678. {
  2679. JSON_THROW(type_error::create(308, detail::concat("cannot use push_back() with ", type_name()), this));
  2680. }
  2681. // transform null object into an array
  2682. if (is_null())
  2683. {
  2684. m_type = value_t::array;
  2685. m_value = value_t::array;
  2686. assert_invariant();
  2687. }
  2688. // add element to array
  2689. const auto old_capacity = m_value.array->capacity();
  2690. m_value.array->push_back(val);
  2691. set_parent(m_value.array->back(), old_capacity);
  2692. }
  2693. /// @brief add an object to an array
  2694. /// @sa https://json.nlohmann.me/api/basic_json/operator+=/
  2695. reference operator+=(const basic_json& val)
  2696. {
  2697. push_back(val);
  2698. return *this;
  2699. }
  2700. /// @brief add an object to an object
  2701. /// @sa https://json.nlohmann.me/api/basic_json/push_back/
  2702. void push_back(const typename object_t::value_type& val)
  2703. {
  2704. // push_back only works for null objects or objects
  2705. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object())))
  2706. {
  2707. JSON_THROW(type_error::create(308, detail::concat("cannot use push_back() with ", type_name()), this));
  2708. }
  2709. // transform null object into an object
  2710. if (is_null())
  2711. {
  2712. m_type = value_t::object;
  2713. m_value = value_t::object;
  2714. assert_invariant();
  2715. }
  2716. // add element to object
  2717. auto res = m_value.object->insert(val);
  2718. set_parent(res.first->second);
  2719. }
  2720. /// @brief add an object to an object
  2721. /// @sa https://json.nlohmann.me/api/basic_json/operator+=/
  2722. reference operator+=(const typename object_t::value_type& val)
  2723. {
  2724. push_back(val);
  2725. return *this;
  2726. }
  2727. /// @brief add an object to an object
  2728. /// @sa https://json.nlohmann.me/api/basic_json/push_back/
  2729. void push_back(initializer_list_t init)
  2730. {
  2731. if (is_object() && init.size() == 2 && (*init.begin())->is_string())
  2732. {
  2733. basic_json&& key = init.begin()->moved_or_copied();
  2734. push_back(typename object_t::value_type(
  2735. std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
  2736. }
  2737. else
  2738. {
  2739. push_back(basic_json(init));
  2740. }
  2741. }
  2742. /// @brief add an object to an object
  2743. /// @sa https://json.nlohmann.me/api/basic_json/operator+=/
  2744. reference operator+=(initializer_list_t init)
  2745. {
  2746. push_back(init);
  2747. return *this;
  2748. }
  2749. /// @brief add an object to an array
  2750. /// @sa https://json.nlohmann.me/api/basic_json/emplace_back/
  2751. template<class... Args>
  2752. reference emplace_back(Args&& ... args)
  2753. {
  2754. // emplace_back only works for null objects or arrays
  2755. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array())))
  2756. {
  2757. JSON_THROW(type_error::create(311, detail::concat("cannot use emplace_back() with ", type_name()), this));
  2758. }
  2759. // transform null object into an array
  2760. if (is_null())
  2761. {
  2762. m_type = value_t::array;
  2763. m_value = value_t::array;
  2764. assert_invariant();
  2765. }
  2766. // add element to array (perfect forwarding)
  2767. const auto old_capacity = m_value.array->capacity();
  2768. m_value.array->emplace_back(std::forward<Args>(args)...);
  2769. return set_parent(m_value.array->back(), old_capacity);
  2770. }
  2771. /// @brief add an object to an object if key does not exist
  2772. /// @sa https://json.nlohmann.me/api/basic_json/emplace/
  2773. template<class... Args>
  2774. std::pair<iterator, bool> emplace(Args&& ... args)
  2775. {
  2776. // emplace only works for null objects or arrays
  2777. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object())))
  2778. {
  2779. JSON_THROW(type_error::create(311, detail::concat("cannot use emplace() with ", type_name()), this));
  2780. }
  2781. // transform null object into an object
  2782. if (is_null())
  2783. {
  2784. m_type = value_t::object;
  2785. m_value = value_t::object;
  2786. assert_invariant();
  2787. }
  2788. // add element to array (perfect forwarding)
  2789. auto res = m_value.object->emplace(std::forward<Args>(args)...);
  2790. set_parent(res.first->second);
  2791. // create result iterator and set iterator to the result of emplace
  2792. auto it = begin();
  2793. it.m_it.object_iterator = res.first;
  2794. // return pair of iterator and boolean
  2795. return {it, res.second};
  2796. }
  2797. /// Helper for insertion of an iterator
  2798. /// @note: This uses std::distance to support GCC 4.8,
  2799. /// see https://github.com/nlohmann/json/pull/1257
  2800. template<typename... Args>
  2801. iterator insert_iterator(const_iterator pos, Args&& ... args)
  2802. {
  2803. iterator result(this);
  2804. JSON_ASSERT(m_value.array != nullptr);
  2805. auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator);
  2806. m_value.array->insert(pos.m_it.array_iterator, std::forward<Args>(args)...);
  2807. result.m_it.array_iterator = m_value.array->begin() + insert_pos;
  2808. // This could have been written as:
  2809. // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
  2810. // but the return value of insert is missing in GCC 4.8, so it is written this way instead.
  2811. set_parents();
  2812. return result;
  2813. }
  2814. /// @brief inserts element into array
  2815. /// @sa https://json.nlohmann.me/api/basic_json/insert/
  2816. iterator insert(const_iterator pos, const basic_json& val)
  2817. {
  2818. // insert only works for arrays
  2819. if (JSON_HEDLEY_LIKELY(is_array()))
  2820. {
  2821. // check if iterator pos fits to this JSON value
  2822. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  2823. {
  2824. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", this));
  2825. }
  2826. // insert to array and return iterator
  2827. return insert_iterator(pos, val);
  2828. }
  2829. JSON_THROW(type_error::create(309, detail::concat("cannot use insert() with ", type_name()), this));
  2830. }
  2831. /// @brief inserts element into array
  2832. /// @sa https://json.nlohmann.me/api/basic_json/insert/
  2833. iterator insert(const_iterator pos, basic_json&& val)
  2834. {
  2835. return insert(pos, val);
  2836. }
  2837. /// @brief inserts copies of element into array
  2838. /// @sa https://json.nlohmann.me/api/basic_json/insert/
  2839. iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
  2840. {
  2841. // insert only works for arrays
  2842. if (JSON_HEDLEY_LIKELY(is_array()))
  2843. {
  2844. // check if iterator pos fits to this JSON value
  2845. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  2846. {
  2847. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", this));
  2848. }
  2849. // insert to array and return iterator
  2850. return insert_iterator(pos, cnt, val);
  2851. }
  2852. JSON_THROW(type_error::create(309, detail::concat("cannot use insert() with ", type_name()), this));
  2853. }
  2854. /// @brief inserts range of elements into array
  2855. /// @sa https://json.nlohmann.me/api/basic_json/insert/
  2856. iterator insert(const_iterator pos, const_iterator first, const_iterator last)
  2857. {
  2858. // insert only works for arrays
  2859. if (JSON_HEDLEY_UNLIKELY(!is_array()))
  2860. {
  2861. JSON_THROW(type_error::create(309, detail::concat("cannot use insert() with ", type_name()), this));
  2862. }
  2863. // check if iterator pos fits to this JSON value
  2864. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  2865. {
  2866. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", this));
  2867. }
  2868. // check if range iterators belong to the same JSON object
  2869. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  2870. {
  2871. JSON_THROW(invalid_iterator::create(210, "iterators do not fit", this));
  2872. }
  2873. if (JSON_HEDLEY_UNLIKELY(first.m_object == this))
  2874. {
  2875. JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container", this));
  2876. }
  2877. // insert to array and return iterator
  2878. return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator);
  2879. }
  2880. /// @brief inserts elements from initializer list into array
  2881. /// @sa https://json.nlohmann.me/api/basic_json/insert/
  2882. iterator insert(const_iterator pos, initializer_list_t ilist)
  2883. {
  2884. // insert only works for arrays
  2885. if (JSON_HEDLEY_UNLIKELY(!is_array()))
  2886. {
  2887. JSON_THROW(type_error::create(309, detail::concat("cannot use insert() with ", type_name()), this));
  2888. }
  2889. // check if iterator pos fits to this JSON value
  2890. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  2891. {
  2892. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", this));
  2893. }
  2894. // insert to array and return iterator
  2895. return insert_iterator(pos, ilist.begin(), ilist.end());
  2896. }
  2897. /// @brief inserts range of elements into object
  2898. /// @sa https://json.nlohmann.me/api/basic_json/insert/
  2899. void insert(const_iterator first, const_iterator last)
  2900. {
  2901. // insert only works for objects
  2902. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  2903. {
  2904. JSON_THROW(type_error::create(309, detail::concat("cannot use insert() with ", type_name()), this));
  2905. }
  2906. // check if range iterators belong to the same JSON object
  2907. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  2908. {
  2909. JSON_THROW(invalid_iterator::create(210, "iterators do not fit", this));
  2910. }
  2911. // passed iterators must belong to objects
  2912. if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object()))
  2913. {
  2914. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects", this));
  2915. }
  2916. m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
  2917. }
  2918. /// @brief updates a JSON object from another object, overwriting existing keys
  2919. /// @sa https://json.nlohmann.me/api/basic_json/update/
  2920. void update(const_reference j, bool merge_objects = false)
  2921. {
  2922. update(j.begin(), j.end(), merge_objects);
  2923. }
  2924. /// @brief updates a JSON object from another object, overwriting existing keys
  2925. /// @sa https://json.nlohmann.me/api/basic_json/update/
  2926. void update(const_iterator first, const_iterator last, bool merge_objects = false)
  2927. {
  2928. // implicitly convert null value to an empty object
  2929. if (is_null())
  2930. {
  2931. m_type = value_t::object;
  2932. m_value.object = create<object_t>();
  2933. assert_invariant();
  2934. }
  2935. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  2936. {
  2937. JSON_THROW(type_error::create(312, detail::concat("cannot use update() with ", type_name()), this));
  2938. }
  2939. // check if range iterators belong to the same JSON object
  2940. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  2941. {
  2942. JSON_THROW(invalid_iterator::create(210, "iterators do not fit", this));
  2943. }
  2944. // passed iterators must belong to objects
  2945. if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object()))
  2946. {
  2947. JSON_THROW(type_error::create(312, detail::concat("cannot use update() with ", first.m_object->type_name()), first.m_object));
  2948. }
  2949. for (auto it = first; it != last; ++it)
  2950. {
  2951. if (merge_objects && it.value().is_object())
  2952. {
  2953. auto it2 = m_value.object->find(it.key());
  2954. if (it2 != m_value.object->end())
  2955. {
  2956. it2->second.update(it.value(), true);
  2957. continue;
  2958. }
  2959. }
  2960. m_value.object->operator[](it.key()) = it.value();
  2961. #if JSON_DIAGNOSTICS
  2962. m_value.object->operator[](it.key()).m_parent = this;
  2963. #endif
  2964. }
  2965. }
  2966. /// @brief exchanges the values
  2967. /// @sa https://json.nlohmann.me/api/basic_json/swap/
  2968. void swap(reference other) noexcept (
  2969. std::is_nothrow_move_constructible<value_t>::value&&
  2970. std::is_nothrow_move_assignable<value_t>::value&&
  2971. std::is_nothrow_move_constructible<json_value>::value&&
  2972. std::is_nothrow_move_assignable<json_value>::value
  2973. )
  2974. {
  2975. std::swap(m_type, other.m_type);
  2976. std::swap(m_value, other.m_value);
  2977. set_parents();
  2978. other.set_parents();
  2979. assert_invariant();
  2980. }
  2981. /// @brief exchanges the values
  2982. /// @sa https://json.nlohmann.me/api/basic_json/swap/
  2983. friend void swap(reference left, reference right) noexcept (
  2984. std::is_nothrow_move_constructible<value_t>::value&&
  2985. std::is_nothrow_move_assignable<value_t>::value&&
  2986. std::is_nothrow_move_constructible<json_value>::value&&
  2987. std::is_nothrow_move_assignable<json_value>::value
  2988. )
  2989. {
  2990. left.swap(right);
  2991. }
  2992. /// @brief exchanges the values
  2993. /// @sa https://json.nlohmann.me/api/basic_json/swap/
  2994. void swap(array_t& other) // NOLINT(bugprone-exception-escape)
  2995. {
  2996. // swap only works for arrays
  2997. if (JSON_HEDLEY_LIKELY(is_array()))
  2998. {
  2999. using std::swap;
  3000. swap(*(m_value.array), other);
  3001. }
  3002. else
  3003. {
  3004. JSON_THROW(type_error::create(310, detail::concat("cannot use swap(array_t&) with ", type_name()), this));
  3005. }
  3006. }
  3007. /// @brief exchanges the values
  3008. /// @sa https://json.nlohmann.me/api/basic_json/swap/
  3009. void swap(object_t& other) // NOLINT(bugprone-exception-escape)
  3010. {
  3011. // swap only works for objects
  3012. if (JSON_HEDLEY_LIKELY(is_object()))
  3013. {
  3014. using std::swap;
  3015. swap(*(m_value.object), other);
  3016. }
  3017. else
  3018. {
  3019. JSON_THROW(type_error::create(310, detail::concat("cannot use swap(object_t&) with ", type_name()), this));
  3020. }
  3021. }
  3022. /// @brief exchanges the values
  3023. /// @sa https://json.nlohmann.me/api/basic_json/swap/
  3024. void swap(string_t& other) // NOLINT(bugprone-exception-escape)
  3025. {
  3026. // swap only works for strings
  3027. if (JSON_HEDLEY_LIKELY(is_string()))
  3028. {
  3029. using std::swap;
  3030. swap(*(m_value.string), other);
  3031. }
  3032. else
  3033. {
  3034. JSON_THROW(type_error::create(310, detail::concat("cannot use swap(string_t&) with ", type_name()), this));
  3035. }
  3036. }
  3037. /// @brief exchanges the values
  3038. /// @sa https://json.nlohmann.me/api/basic_json/swap/
  3039. void swap(binary_t& other) // NOLINT(bugprone-exception-escape)
  3040. {
  3041. // swap only works for strings
  3042. if (JSON_HEDLEY_LIKELY(is_binary()))
  3043. {
  3044. using std::swap;
  3045. swap(*(m_value.binary), other);
  3046. }
  3047. else
  3048. {
  3049. JSON_THROW(type_error::create(310, detail::concat("cannot use swap(binary_t&) with ", type_name()), this));
  3050. }
  3051. }
  3052. /// @brief exchanges the values
  3053. /// @sa https://json.nlohmann.me/api/basic_json/swap/
  3054. void swap(typename binary_t::container_type& other) // NOLINT(bugprone-exception-escape)
  3055. {
  3056. // swap only works for strings
  3057. if (JSON_HEDLEY_LIKELY(is_binary()))
  3058. {
  3059. using std::swap;
  3060. swap(*(m_value.binary), other);
  3061. }
  3062. else
  3063. {
  3064. JSON_THROW(type_error::create(310, detail::concat("cannot use swap(binary_t::container_type&) with ", type_name()), this));
  3065. }
  3066. }
  3067. /// @}
  3068. //////////////////////////////////////////
  3069. // lexicographical comparison operators //
  3070. //////////////////////////////////////////
  3071. /// @name lexicographical comparison operators
  3072. /// @{
  3073. // note parentheses around operands are necessary; see
  3074. // https://github.com/nlohmann/json/issues/1530
  3075. #define JSON_IMPLEMENT_OPERATOR(op, null_result, unordered_result, default_result) \
  3076. const auto lhs_type = lhs.type(); \
  3077. const auto rhs_type = rhs.type(); \
  3078. \
  3079. if (lhs_type == rhs_type) /* NOLINT(readability/braces) */ \
  3080. { \
  3081. switch (lhs_type) \
  3082. { \
  3083. case value_t::array: \
  3084. return (*lhs.m_value.array) op (*rhs.m_value.array); \
  3085. \
  3086. case value_t::object: \
  3087. return (*lhs.m_value.object) op (*rhs.m_value.object); \
  3088. \
  3089. case value_t::null: \
  3090. return (null_result); \
  3091. \
  3092. case value_t::string: \
  3093. return (*lhs.m_value.string) op (*rhs.m_value.string); \
  3094. \
  3095. case value_t::boolean: \
  3096. return (lhs.m_value.boolean) op (rhs.m_value.boolean); \
  3097. \
  3098. case value_t::number_integer: \
  3099. return (lhs.m_value.number_integer) op (rhs.m_value.number_integer); \
  3100. \
  3101. case value_t::number_unsigned: \
  3102. return (lhs.m_value.number_unsigned) op (rhs.m_value.number_unsigned); \
  3103. \
  3104. case value_t::number_float: \
  3105. return (lhs.m_value.number_float) op (rhs.m_value.number_float); \
  3106. \
  3107. case value_t::binary: \
  3108. return (*lhs.m_value.binary) op (*rhs.m_value.binary); \
  3109. \
  3110. case value_t::discarded: \
  3111. default: \
  3112. return (unordered_result); \
  3113. } \
  3114. } \
  3115. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float) \
  3116. { \
  3117. return static_cast<number_float_t>(lhs.m_value.number_integer) op rhs.m_value.number_float; \
  3118. } \
  3119. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer) \
  3120. { \
  3121. return lhs.m_value.number_float op static_cast<number_float_t>(rhs.m_value.number_integer); \
  3122. } \
  3123. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float) \
  3124. { \
  3125. return static_cast<number_float_t>(lhs.m_value.number_unsigned) op rhs.m_value.number_float; \
  3126. } \
  3127. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned) \
  3128. { \
  3129. return lhs.m_value.number_float op static_cast<number_float_t>(rhs.m_value.number_unsigned); \
  3130. } \
  3131. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer) \
  3132. { \
  3133. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) op rhs.m_value.number_integer; \
  3134. } \
  3135. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned) \
  3136. { \
  3137. return lhs.m_value.number_integer op static_cast<number_integer_t>(rhs.m_value.number_unsigned); \
  3138. } \
  3139. else if(compares_unordered(lhs, rhs))\
  3140. {\
  3141. return (unordered_result);\
  3142. }\
  3143. \
  3144. return (default_result);
  3145. JSON_PRIVATE_UNLESS_TESTED:
  3146. // returns true if:
  3147. // - any operand is NaN and the other operand is of number type
  3148. // - any operand is discarded
  3149. // in legacy mode, discarded values are considered ordered if
  3150. // an operation is computed as an odd number of inverses of others
  3151. static bool compares_unordered(const_reference lhs, const_reference rhs, bool inverse = false) noexcept
  3152. {
  3153. if ((lhs.is_number_float() && std::isnan(lhs.m_value.number_float) && rhs.is_number())
  3154. || (rhs.is_number_float() && std::isnan(rhs.m_value.number_float) && lhs.is_number()))
  3155. {
  3156. return true;
  3157. }
  3158. #if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON
  3159. return (lhs.is_discarded() || rhs.is_discarded()) && !inverse;
  3160. #else
  3161. static_cast<void>(inverse);
  3162. return lhs.is_discarded() || rhs.is_discarded();
  3163. #endif
  3164. }
  3165. private:
  3166. bool compares_unordered(const_reference rhs, bool inverse = false) const noexcept
  3167. {
  3168. return compares_unordered(*this, rhs, inverse);
  3169. }
  3170. public:
  3171. #if JSON_HAS_THREE_WAY_COMPARISON
  3172. /// @brief comparison: equal
  3173. /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/
  3174. bool operator==(const_reference rhs) const noexcept
  3175. {
  3176. #ifdef __GNUC__
  3177. #pragma GCC diagnostic push
  3178. #pragma GCC diagnostic ignored "-Wfloat-equal"
  3179. #endif
  3180. const_reference lhs = *this;
  3181. JSON_IMPLEMENT_OPERATOR( ==, true, false, false)
  3182. #ifdef __GNUC__
  3183. #pragma GCC diagnostic pop
  3184. #endif
  3185. }
  3186. /// @brief comparison: equal
  3187. /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/
  3188. template<typename ScalarType>
  3189. requires std::is_scalar_v<ScalarType>
  3190. bool operator==(ScalarType rhs) const noexcept
  3191. {
  3192. return *this == basic_json(rhs);
  3193. }
  3194. /// @brief comparison: not equal
  3195. /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/
  3196. bool operator!=(const_reference rhs) const noexcept
  3197. {
  3198. if (compares_unordered(rhs, true))
  3199. {
  3200. return false;
  3201. }
  3202. return !operator==(rhs);
  3203. }
  3204. /// @brief comparison: 3-way
  3205. /// @sa https://json.nlohmann.me/api/basic_json/operator_spaceship/
  3206. std::partial_ordering operator<=>(const_reference rhs) const noexcept // *NOPAD*
  3207. {
  3208. const_reference lhs = *this;
  3209. // default_result is used if we cannot compare values. In that case,
  3210. // we compare types.
  3211. JSON_IMPLEMENT_OPERATOR(<=>, // *NOPAD*
  3212. std::partial_ordering::equivalent,
  3213. std::partial_ordering::unordered,
  3214. lhs_type <=> rhs_type) // *NOPAD*
  3215. }
  3216. /// @brief comparison: 3-way
  3217. /// @sa https://json.nlohmann.me/api/basic_json/operator_spaceship/
  3218. template<typename ScalarType>
  3219. requires std::is_scalar_v<ScalarType>
  3220. std::partial_ordering operator<=>(ScalarType rhs) const noexcept // *NOPAD*
  3221. {
  3222. return *this <=> basic_json(rhs); // *NOPAD*
  3223. }
  3224. #if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON
  3225. // all operators that are computed as an odd number of inverses of others
  3226. // need to be overloaded to emulate the legacy comparison behavior
  3227. /// @brief comparison: less than or equal
  3228. /// @sa https://json.nlohmann.me/api/basic_json/operator_le/
  3229. JSON_HEDLEY_DEPRECATED_FOR(3.11.0, undef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON)
  3230. bool operator<=(const_reference rhs) const noexcept
  3231. {
  3232. if (compares_unordered(rhs, true))
  3233. {
  3234. return false;
  3235. }
  3236. return !(rhs < *this);
  3237. }
  3238. /// @brief comparison: less than or equal
  3239. /// @sa https://json.nlohmann.me/api/basic_json/operator_le/
  3240. template<typename ScalarType>
  3241. requires std::is_scalar_v<ScalarType>
  3242. bool operator<=(ScalarType rhs) const noexcept
  3243. {
  3244. return *this <= basic_json(rhs);
  3245. }
  3246. /// @brief comparison: greater than or equal
  3247. /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/
  3248. JSON_HEDLEY_DEPRECATED_FOR(3.11.0, undef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON)
  3249. bool operator>=(const_reference rhs) const noexcept
  3250. {
  3251. if (compares_unordered(rhs, true))
  3252. {
  3253. return false;
  3254. }
  3255. return !(*this < rhs);
  3256. }
  3257. /// @brief comparison: greater than or equal
  3258. /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/
  3259. template<typename ScalarType>
  3260. requires std::is_scalar_v<ScalarType>
  3261. bool operator>=(ScalarType rhs) const noexcept
  3262. {
  3263. return *this >= basic_json(rhs);
  3264. }
  3265. #endif
  3266. #else
  3267. /// @brief comparison: equal
  3268. /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/
  3269. friend bool operator==(const_reference lhs, const_reference rhs) noexcept
  3270. {
  3271. #ifdef __GNUC__
  3272. #pragma GCC diagnostic push
  3273. #pragma GCC diagnostic ignored "-Wfloat-equal"
  3274. #endif
  3275. JSON_IMPLEMENT_OPERATOR( ==, true, false, false)
  3276. #ifdef __GNUC__
  3277. #pragma GCC diagnostic pop
  3278. #endif
  3279. }
  3280. /// @brief comparison: equal
  3281. /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/
  3282. template<typename ScalarType, typename std::enable_if<
  3283. std::is_scalar<ScalarType>::value, int>::type = 0>
  3284. friend bool operator==(const_reference lhs, ScalarType rhs) noexcept
  3285. {
  3286. return lhs == basic_json(rhs);
  3287. }
  3288. /// @brief comparison: equal
  3289. /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/
  3290. template<typename ScalarType, typename std::enable_if<
  3291. std::is_scalar<ScalarType>::value, int>::type = 0>
  3292. friend bool operator==(ScalarType lhs, const_reference rhs) noexcept
  3293. {
  3294. return basic_json(lhs) == rhs;
  3295. }
  3296. /// @brief comparison: not equal
  3297. /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/
  3298. friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
  3299. {
  3300. if (compares_unordered(lhs, rhs, true))
  3301. {
  3302. return false;
  3303. }
  3304. return !(lhs == rhs);
  3305. }
  3306. /// @brief comparison: not equal
  3307. /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/
  3308. template<typename ScalarType, typename std::enable_if<
  3309. std::is_scalar<ScalarType>::value, int>::type = 0>
  3310. friend bool operator!=(const_reference lhs, ScalarType rhs) noexcept
  3311. {
  3312. return lhs != basic_json(rhs);
  3313. }
  3314. /// @brief comparison: not equal
  3315. /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/
  3316. template<typename ScalarType, typename std::enable_if<
  3317. std::is_scalar<ScalarType>::value, int>::type = 0>
  3318. friend bool operator!=(ScalarType lhs, const_reference rhs) noexcept
  3319. {
  3320. return basic_json(lhs) != rhs;
  3321. }
  3322. /// @brief comparison: less than
  3323. /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/
  3324. friend bool operator<(const_reference lhs, const_reference rhs) noexcept
  3325. {
  3326. // default_result is used if we cannot compare values. In that case,
  3327. // we compare types. Note we have to call the operator explicitly,
  3328. // because MSVC has problems otherwise.
  3329. JSON_IMPLEMENT_OPERATOR( <, false, false, operator<(lhs_type, rhs_type))
  3330. }
  3331. /// @brief comparison: less than
  3332. /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/
  3333. template<typename ScalarType, typename std::enable_if<
  3334. std::is_scalar<ScalarType>::value, int>::type = 0>
  3335. friend bool operator<(const_reference lhs, ScalarType rhs) noexcept
  3336. {
  3337. return lhs < basic_json(rhs);
  3338. }
  3339. /// @brief comparison: less than
  3340. /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/
  3341. template<typename ScalarType, typename std::enable_if<
  3342. std::is_scalar<ScalarType>::value, int>::type = 0>
  3343. friend bool operator<(ScalarType lhs, const_reference rhs) noexcept
  3344. {
  3345. return basic_json(lhs) < rhs;
  3346. }
  3347. /// @brief comparison: less than or equal
  3348. /// @sa https://json.nlohmann.me/api/basic_json/operator_le/
  3349. friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
  3350. {
  3351. if (compares_unordered(lhs, rhs, true))
  3352. {
  3353. return false;
  3354. }
  3355. return !(rhs < lhs);
  3356. }
  3357. /// @brief comparison: less than or equal
  3358. /// @sa https://json.nlohmann.me/api/basic_json/operator_le/
  3359. template<typename ScalarType, typename std::enable_if<
  3360. std::is_scalar<ScalarType>::value, int>::type = 0>
  3361. friend bool operator<=(const_reference lhs, ScalarType rhs) noexcept
  3362. {
  3363. return lhs <= basic_json(rhs);
  3364. }
  3365. /// @brief comparison: less than or equal
  3366. /// @sa https://json.nlohmann.me/api/basic_json/operator_le/
  3367. template<typename ScalarType, typename std::enable_if<
  3368. std::is_scalar<ScalarType>::value, int>::type = 0>
  3369. friend bool operator<=(ScalarType lhs, const_reference rhs) noexcept
  3370. {
  3371. return basic_json(lhs) <= rhs;
  3372. }
  3373. /// @brief comparison: greater than
  3374. /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/
  3375. friend bool operator>(const_reference lhs, const_reference rhs) noexcept
  3376. {
  3377. // double inverse
  3378. if (compares_unordered(lhs, rhs))
  3379. {
  3380. return false;
  3381. }
  3382. return !(lhs <= rhs);
  3383. }
  3384. /// @brief comparison: greater than
  3385. /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/
  3386. template<typename ScalarType, typename std::enable_if<
  3387. std::is_scalar<ScalarType>::value, int>::type = 0>
  3388. friend bool operator>(const_reference lhs, ScalarType rhs) noexcept
  3389. {
  3390. return lhs > basic_json(rhs);
  3391. }
  3392. /// @brief comparison: greater than
  3393. /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/
  3394. template<typename ScalarType, typename std::enable_if<
  3395. std::is_scalar<ScalarType>::value, int>::type = 0>
  3396. friend bool operator>(ScalarType lhs, const_reference rhs) noexcept
  3397. {
  3398. return basic_json(lhs) > rhs;
  3399. }
  3400. /// @brief comparison: greater than or equal
  3401. /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/
  3402. friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
  3403. {
  3404. if (compares_unordered(lhs, rhs, true))
  3405. {
  3406. return false;
  3407. }
  3408. return !(lhs < rhs);
  3409. }
  3410. /// @brief comparison: greater than or equal
  3411. /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/
  3412. template<typename ScalarType, typename std::enable_if<
  3413. std::is_scalar<ScalarType>::value, int>::type = 0>
  3414. friend bool operator>=(const_reference lhs, ScalarType rhs) noexcept
  3415. {
  3416. return lhs >= basic_json(rhs);
  3417. }
  3418. /// @brief comparison: greater than or equal
  3419. /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/
  3420. template<typename ScalarType, typename std::enable_if<
  3421. std::is_scalar<ScalarType>::value, int>::type = 0>
  3422. friend bool operator>=(ScalarType lhs, const_reference rhs) noexcept
  3423. {
  3424. return basic_json(lhs) >= rhs;
  3425. }
  3426. #endif
  3427. #undef JSON_IMPLEMENT_OPERATOR
  3428. /// @}
  3429. ///////////////////
  3430. // serialization //
  3431. ///////////////////
  3432. /// @name serialization
  3433. /// @{
  3434. #ifndef JSON_NO_IO
  3435. /// @brief serialize to stream
  3436. /// @sa https://json.nlohmann.me/api/basic_json/operator_ltlt/
  3437. friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
  3438. {
  3439. // read width member and use it as indentation parameter if nonzero
  3440. const bool pretty_print = o.width() > 0;
  3441. const auto indentation = pretty_print ? o.width() : 0;
  3442. // reset width to 0 for subsequent calls to this stream
  3443. o.width(0);
  3444. // do the actual serialization
  3445. serializer s(detail::output_adapter<char>(o), o.fill());
  3446. s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
  3447. return o;
  3448. }
  3449. /// @brief serialize to stream
  3450. /// @sa https://json.nlohmann.me/api/basic_json/operator_ltlt/
  3451. /// @deprecated This function is deprecated since 3.0.0 and will be removed in
  3452. /// version 4.0.0 of the library. Please use
  3453. /// operator<<(std::ostream&, const basic_json&) instead; that is,
  3454. /// replace calls like `j >> o;` with `o << j;`.
  3455. JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator<<(std::ostream&, const basic_json&))
  3456. friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
  3457. {
  3458. return o << j;
  3459. }
  3460. #endif // JSON_NO_IO
  3461. /// @}
  3462. /////////////////////
  3463. // deserialization //
  3464. /////////////////////
  3465. /// @name deserialization
  3466. /// @{
  3467. /// @brief deserialize from a compatible input
  3468. /// @sa https://json.nlohmann.me/api/basic_json/parse/
  3469. template<typename InputType>
  3470. JSON_HEDLEY_WARN_UNUSED_RESULT
  3471. static basic_json parse(InputType&& i,
  3472. const parser_callback_t cb = nullptr,
  3473. const bool allow_exceptions = true,
  3474. const bool ignore_comments = false)
  3475. {
  3476. basic_json result;
  3477. parser(detail::input_adapter(std::forward<InputType>(i)), cb, allow_exceptions, ignore_comments).parse(true, result);
  3478. return result;
  3479. }
  3480. /// @brief deserialize from a pair of character iterators
  3481. /// @sa https://json.nlohmann.me/api/basic_json/parse/
  3482. template<typename IteratorType>
  3483. JSON_HEDLEY_WARN_UNUSED_RESULT
  3484. static basic_json parse(IteratorType first,
  3485. IteratorType last,
  3486. const parser_callback_t cb = nullptr,
  3487. const bool allow_exceptions = true,
  3488. const bool ignore_comments = false)
  3489. {
  3490. basic_json result;
  3491. parser(detail::input_adapter(std::move(first), std::move(last)), cb, allow_exceptions, ignore_comments).parse(true, result);
  3492. return result;
  3493. }
  3494. JSON_HEDLEY_WARN_UNUSED_RESULT
  3495. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, parse(ptr, ptr + len))
  3496. static basic_json parse(detail::span_input_adapter&& i,
  3497. const parser_callback_t cb = nullptr,
  3498. const bool allow_exceptions = true,
  3499. const bool ignore_comments = false)
  3500. {
  3501. basic_json result;
  3502. parser(i.get(), cb, allow_exceptions, ignore_comments).parse(true, result);
  3503. return result;
  3504. }
  3505. /// @brief check if the input is valid JSON
  3506. /// @sa https://json.nlohmann.me/api/basic_json/accept/
  3507. template<typename InputType>
  3508. static bool accept(InputType&& i,
  3509. const bool ignore_comments = false)
  3510. {
  3511. return parser(detail::input_adapter(std::forward<InputType>(i)), nullptr, false, ignore_comments).accept(true);
  3512. }
  3513. /// @brief check if the input is valid JSON
  3514. /// @sa https://json.nlohmann.me/api/basic_json/accept/
  3515. template<typename IteratorType>
  3516. static bool accept(IteratorType first, IteratorType last,
  3517. const bool ignore_comments = false)
  3518. {
  3519. return parser(detail::input_adapter(std::move(first), std::move(last)), nullptr, false, ignore_comments).accept(true);
  3520. }
  3521. JSON_HEDLEY_WARN_UNUSED_RESULT
  3522. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, accept(ptr, ptr + len))
  3523. static bool accept(detail::span_input_adapter&& i,
  3524. const bool ignore_comments = false)
  3525. {
  3526. return parser(i.get(), nullptr, false, ignore_comments).accept(true);
  3527. }
  3528. /// @brief generate SAX events
  3529. /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/
  3530. template <typename InputType, typename SAX>
  3531. JSON_HEDLEY_NON_NULL(2)
  3532. static bool sax_parse(InputType&& i, SAX* sax,
  3533. input_format_t format = input_format_t::json,
  3534. const bool strict = true,
  3535. const bool ignore_comments = false)
  3536. {
  3537. auto ia = detail::input_adapter(std::forward<InputType>(i));
  3538. return format == input_format_t::json
  3539. ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
  3540. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia), format).sax_parse(format, sax, strict);
  3541. }
  3542. /// @brief generate SAX events
  3543. /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/
  3544. template<class IteratorType, class SAX>
  3545. JSON_HEDLEY_NON_NULL(3)
  3546. static bool sax_parse(IteratorType first, IteratorType last, SAX* sax,
  3547. input_format_t format = input_format_t::json,
  3548. const bool strict = true,
  3549. const bool ignore_comments = false)
  3550. {
  3551. auto ia = detail::input_adapter(std::move(first), std::move(last));
  3552. return format == input_format_t::json
  3553. ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
  3554. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia), format).sax_parse(format, sax, strict);
  3555. }
  3556. /// @brief generate SAX events
  3557. /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/
  3558. /// @deprecated This function is deprecated since 3.8.0 and will be removed in
  3559. /// version 4.0.0 of the library. Please use
  3560. /// sax_parse(ptr, ptr + len) instead.
  3561. template <typename SAX>
  3562. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, sax_parse(ptr, ptr + len, ...))
  3563. JSON_HEDLEY_NON_NULL(2)
  3564. static bool sax_parse(detail::span_input_adapter&& i, SAX* sax,
  3565. input_format_t format = input_format_t::json,
  3566. const bool strict = true,
  3567. const bool ignore_comments = false)
  3568. {
  3569. auto ia = i.get();
  3570. return format == input_format_t::json
  3571. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  3572. ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
  3573. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  3574. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia), format).sax_parse(format, sax, strict);
  3575. }
  3576. #ifndef JSON_NO_IO
  3577. /// @brief deserialize from stream
  3578. /// @sa https://json.nlohmann.me/api/basic_json/operator_gtgt/
  3579. /// @deprecated This stream operator is deprecated since 3.0.0 and will be removed in
  3580. /// version 4.0.0 of the library. Please use
  3581. /// operator>>(std::istream&, basic_json&) instead; that is,
  3582. /// replace calls like `j << i;` with `i >> j;`.
  3583. JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator>>(std::istream&, basic_json&))
  3584. friend std::istream& operator<<(basic_json& j, std::istream& i)
  3585. {
  3586. return operator>>(i, j);
  3587. }
  3588. /// @brief deserialize from stream
  3589. /// @sa https://json.nlohmann.me/api/basic_json/operator_gtgt/
  3590. friend std::istream& operator>>(std::istream& i, basic_json& j)
  3591. {
  3592. parser(detail::input_adapter(i)).parse(false, j);
  3593. return i;
  3594. }
  3595. #endif // JSON_NO_IO
  3596. /// @}
  3597. ///////////////////////////
  3598. // convenience functions //
  3599. ///////////////////////////
  3600. /// @brief return the type as string
  3601. /// @sa https://json.nlohmann.me/api/basic_json/type_name/
  3602. JSON_HEDLEY_RETURNS_NON_NULL
  3603. const char* type_name() const noexcept
  3604. {
  3605. switch (m_type)
  3606. {
  3607. case value_t::null:
  3608. return "null";
  3609. case value_t::object:
  3610. return "object";
  3611. case value_t::array:
  3612. return "array";
  3613. case value_t::string:
  3614. return "string";
  3615. case value_t::boolean:
  3616. return "boolean";
  3617. case value_t::binary:
  3618. return "binary";
  3619. case value_t::discarded:
  3620. return "discarded";
  3621. case value_t::number_integer:
  3622. case value_t::number_unsigned:
  3623. case value_t::number_float:
  3624. default:
  3625. return "number";
  3626. }
  3627. }
  3628. JSON_PRIVATE_UNLESS_TESTED:
  3629. //////////////////////
  3630. // member variables //
  3631. //////////////////////
  3632. /// the type of the current element
  3633. value_t m_type = value_t::null;
  3634. /// the value of the current element
  3635. json_value m_value = {};
  3636. #if JSON_DIAGNOSTICS
  3637. /// a pointer to a parent value (for debugging purposes)
  3638. basic_json* m_parent = nullptr;
  3639. #endif
  3640. //////////////////////////////////////////
  3641. // binary serialization/deserialization //
  3642. //////////////////////////////////////////
  3643. /// @name binary serialization/deserialization support
  3644. /// @{
  3645. public:
  3646. /// @brief create a CBOR serialization of a given JSON value
  3647. /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/
  3648. static std::vector<std::uint8_t> to_cbor(const basic_json& j)
  3649. {
  3650. std::vector<std::uint8_t> result;
  3651. to_cbor(j, result);
  3652. return result;
  3653. }
  3654. /// @brief create a CBOR serialization of a given JSON value
  3655. /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/
  3656. static void to_cbor(const basic_json& j, detail::output_adapter<std::uint8_t> o)
  3657. {
  3658. binary_writer<std::uint8_t>(o).write_cbor(j);
  3659. }
  3660. /// @brief create a CBOR serialization of a given JSON value
  3661. /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/
  3662. static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
  3663. {
  3664. binary_writer<char>(o).write_cbor(j);
  3665. }
  3666. /// @brief create a MessagePack serialization of a given JSON value
  3667. /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/
  3668. static std::vector<std::uint8_t> to_msgpack(const basic_json& j)
  3669. {
  3670. std::vector<std::uint8_t> result;
  3671. to_msgpack(j, result);
  3672. return result;
  3673. }
  3674. /// @brief create a MessagePack serialization of a given JSON value
  3675. /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/
  3676. static void to_msgpack(const basic_json& j, detail::output_adapter<std::uint8_t> o)
  3677. {
  3678. binary_writer<std::uint8_t>(o).write_msgpack(j);
  3679. }
  3680. /// @brief create a MessagePack serialization of a given JSON value
  3681. /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/
  3682. static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
  3683. {
  3684. binary_writer<char>(o).write_msgpack(j);
  3685. }
  3686. /// @brief create a UBJSON serialization of a given JSON value
  3687. /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/
  3688. static std::vector<std::uint8_t> to_ubjson(const basic_json& j,
  3689. const bool use_size = false,
  3690. const bool use_type = false)
  3691. {
  3692. std::vector<std::uint8_t> result;
  3693. to_ubjson(j, result, use_size, use_type);
  3694. return result;
  3695. }
  3696. /// @brief create a UBJSON serialization of a given JSON value
  3697. /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/
  3698. static void to_ubjson(const basic_json& j, detail::output_adapter<std::uint8_t> o,
  3699. const bool use_size = false, const bool use_type = false)
  3700. {
  3701. binary_writer<std::uint8_t>(o).write_ubjson(j, use_size, use_type);
  3702. }
  3703. /// @brief create a UBJSON serialization of a given JSON value
  3704. /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/
  3705. static void to_ubjson(const basic_json& j, detail::output_adapter<char> o,
  3706. const bool use_size = false, const bool use_type = false)
  3707. {
  3708. binary_writer<char>(o).write_ubjson(j, use_size, use_type);
  3709. }
  3710. /// @brief create a BJData serialization of a given JSON value
  3711. /// @sa https://json.nlohmann.me/api/basic_json/to_bjdata/
  3712. static std::vector<std::uint8_t> to_bjdata(const basic_json& j,
  3713. const bool use_size = false,
  3714. const bool use_type = false)
  3715. {
  3716. std::vector<std::uint8_t> result;
  3717. to_bjdata(j, result, use_size, use_type);
  3718. return result;
  3719. }
  3720. /// @brief create a BJData serialization of a given JSON value
  3721. /// @sa https://json.nlohmann.me/api/basic_json/to_bjdata/
  3722. static void to_bjdata(const basic_json& j, detail::output_adapter<std::uint8_t> o,
  3723. const bool use_size = false, const bool use_type = false)
  3724. {
  3725. binary_writer<std::uint8_t>(o).write_ubjson(j, use_size, use_type, true, true);
  3726. }
  3727. /// @brief create a BJData serialization of a given JSON value
  3728. /// @sa https://json.nlohmann.me/api/basic_json/to_bjdata/
  3729. static void to_bjdata(const basic_json& j, detail::output_adapter<char> o,
  3730. const bool use_size = false, const bool use_type = false)
  3731. {
  3732. binary_writer<char>(o).write_ubjson(j, use_size, use_type, true, true);
  3733. }
  3734. /// @brief create a BSON serialization of a given JSON value
  3735. /// @sa https://json.nlohmann.me/api/basic_json/to_bson/
  3736. static std::vector<std::uint8_t> to_bson(const basic_json& j)
  3737. {
  3738. std::vector<std::uint8_t> result;
  3739. to_bson(j, result);
  3740. return result;
  3741. }
  3742. /// @brief create a BSON serialization of a given JSON value
  3743. /// @sa https://json.nlohmann.me/api/basic_json/to_bson/
  3744. static void to_bson(const basic_json& j, detail::output_adapter<std::uint8_t> o)
  3745. {
  3746. binary_writer<std::uint8_t>(o).write_bson(j);
  3747. }
  3748. /// @brief create a BSON serialization of a given JSON value
  3749. /// @sa https://json.nlohmann.me/api/basic_json/to_bson/
  3750. static void to_bson(const basic_json& j, detail::output_adapter<char> o)
  3751. {
  3752. binary_writer<char>(o).write_bson(j);
  3753. }
  3754. /// @brief create a JSON value from an input in CBOR format
  3755. /// @sa https://json.nlohmann.me/api/basic_json/from_cbor/
  3756. template<typename InputType>
  3757. JSON_HEDLEY_WARN_UNUSED_RESULT
  3758. static basic_json from_cbor(InputType&& i,
  3759. const bool strict = true,
  3760. const bool allow_exceptions = true,
  3761. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  3762. {
  3763. basic_json result;
  3764. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  3765. auto ia = detail::input_adapter(std::forward<InputType>(i));
  3766. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::cbor).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler);
  3767. return res ? result : basic_json(value_t::discarded);
  3768. }
  3769. /// @brief create a JSON value from an input in CBOR format
  3770. /// @sa https://json.nlohmann.me/api/basic_json/from_cbor/
  3771. template<typename IteratorType>
  3772. JSON_HEDLEY_WARN_UNUSED_RESULT
  3773. static basic_json from_cbor(IteratorType first, IteratorType last,
  3774. const bool strict = true,
  3775. const bool allow_exceptions = true,
  3776. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  3777. {
  3778. basic_json result;
  3779. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  3780. auto ia = detail::input_adapter(std::move(first), std::move(last));
  3781. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::cbor).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler);
  3782. return res ? result : basic_json(value_t::discarded);
  3783. }
  3784. template<typename T>
  3785. JSON_HEDLEY_WARN_UNUSED_RESULT
  3786. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len))
  3787. static basic_json from_cbor(const T* ptr, std::size_t len,
  3788. const bool strict = true,
  3789. const bool allow_exceptions = true,
  3790. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  3791. {
  3792. return from_cbor(ptr, ptr + len, strict, allow_exceptions, tag_handler);
  3793. }
  3794. JSON_HEDLEY_WARN_UNUSED_RESULT
  3795. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len))
  3796. static basic_json from_cbor(detail::span_input_adapter&& i,
  3797. const bool strict = true,
  3798. const bool allow_exceptions = true,
  3799. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  3800. {
  3801. basic_json result;
  3802. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  3803. auto ia = i.get();
  3804. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  3805. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::cbor).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler);
  3806. return res ? result : basic_json(value_t::discarded);
  3807. }
  3808. /// @brief create a JSON value from an input in MessagePack format
  3809. /// @sa https://json.nlohmann.me/api/basic_json/from_msgpack/
  3810. template<typename InputType>
  3811. JSON_HEDLEY_WARN_UNUSED_RESULT
  3812. static basic_json from_msgpack(InputType&& i,
  3813. const bool strict = true,
  3814. const bool allow_exceptions = true)
  3815. {
  3816. basic_json result;
  3817. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  3818. auto ia = detail::input_adapter(std::forward<InputType>(i));
  3819. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::msgpack).sax_parse(input_format_t::msgpack, &sdp, strict);
  3820. return res ? result : basic_json(value_t::discarded);
  3821. }
  3822. /// @brief create a JSON value from an input in MessagePack format
  3823. /// @sa https://json.nlohmann.me/api/basic_json/from_msgpack/
  3824. template<typename IteratorType>
  3825. JSON_HEDLEY_WARN_UNUSED_RESULT
  3826. static basic_json from_msgpack(IteratorType first, IteratorType last,
  3827. const bool strict = true,
  3828. const bool allow_exceptions = true)
  3829. {
  3830. basic_json result;
  3831. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  3832. auto ia = detail::input_adapter(std::move(first), std::move(last));
  3833. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::msgpack).sax_parse(input_format_t::msgpack, &sdp, strict);
  3834. return res ? result : basic_json(value_t::discarded);
  3835. }
  3836. template<typename T>
  3837. JSON_HEDLEY_WARN_UNUSED_RESULT
  3838. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len))
  3839. static basic_json from_msgpack(const T* ptr, std::size_t len,
  3840. const bool strict = true,
  3841. const bool allow_exceptions = true)
  3842. {
  3843. return from_msgpack(ptr, ptr + len, strict, allow_exceptions);
  3844. }
  3845. JSON_HEDLEY_WARN_UNUSED_RESULT
  3846. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len))
  3847. static basic_json from_msgpack(detail::span_input_adapter&& i,
  3848. const bool strict = true,
  3849. const bool allow_exceptions = true)
  3850. {
  3851. basic_json result;
  3852. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  3853. auto ia = i.get();
  3854. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  3855. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::msgpack).sax_parse(input_format_t::msgpack, &sdp, strict);
  3856. return res ? result : basic_json(value_t::discarded);
  3857. }
  3858. /// @brief create a JSON value from an input in UBJSON format
  3859. /// @sa https://json.nlohmann.me/api/basic_json/from_ubjson/
  3860. template<typename InputType>
  3861. JSON_HEDLEY_WARN_UNUSED_RESULT
  3862. static basic_json from_ubjson(InputType&& i,
  3863. const bool strict = true,
  3864. const bool allow_exceptions = true)
  3865. {
  3866. basic_json result;
  3867. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  3868. auto ia = detail::input_adapter(std::forward<InputType>(i));
  3869. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::ubjson).sax_parse(input_format_t::ubjson, &sdp, strict);
  3870. return res ? result : basic_json(value_t::discarded);
  3871. }
  3872. /// @brief create a JSON value from an input in UBJSON format
  3873. /// @sa https://json.nlohmann.me/api/basic_json/from_ubjson/
  3874. template<typename IteratorType>
  3875. JSON_HEDLEY_WARN_UNUSED_RESULT
  3876. static basic_json from_ubjson(IteratorType first, IteratorType last,
  3877. const bool strict = true,
  3878. const bool allow_exceptions = true)
  3879. {
  3880. basic_json result;
  3881. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  3882. auto ia = detail::input_adapter(std::move(first), std::move(last));
  3883. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::ubjson).sax_parse(input_format_t::ubjson, &sdp, strict);
  3884. return res ? result : basic_json(value_t::discarded);
  3885. }
  3886. template<typename T>
  3887. JSON_HEDLEY_WARN_UNUSED_RESULT
  3888. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len))
  3889. static basic_json from_ubjson(const T* ptr, std::size_t len,
  3890. const bool strict = true,
  3891. const bool allow_exceptions = true)
  3892. {
  3893. return from_ubjson(ptr, ptr + len, strict, allow_exceptions);
  3894. }
  3895. JSON_HEDLEY_WARN_UNUSED_RESULT
  3896. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len))
  3897. static basic_json from_ubjson(detail::span_input_adapter&& i,
  3898. const bool strict = true,
  3899. const bool allow_exceptions = true)
  3900. {
  3901. basic_json result;
  3902. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  3903. auto ia = i.get();
  3904. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  3905. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::ubjson).sax_parse(input_format_t::ubjson, &sdp, strict);
  3906. return res ? result : basic_json(value_t::discarded);
  3907. }
  3908. /// @brief create a JSON value from an input in BJData format
  3909. /// @sa https://json.nlohmann.me/api/basic_json/from_bjdata/
  3910. template<typename InputType>
  3911. JSON_HEDLEY_WARN_UNUSED_RESULT
  3912. static basic_json from_bjdata(InputType&& i,
  3913. const bool strict = true,
  3914. const bool allow_exceptions = true)
  3915. {
  3916. basic_json result;
  3917. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  3918. auto ia = detail::input_adapter(std::forward<InputType>(i));
  3919. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::bjdata).sax_parse(input_format_t::bjdata, &sdp, strict);
  3920. return res ? result : basic_json(value_t::discarded);
  3921. }
  3922. /// @brief create a JSON value from an input in BJData format
  3923. /// @sa https://json.nlohmann.me/api/basic_json/from_bjdata/
  3924. template<typename IteratorType>
  3925. JSON_HEDLEY_WARN_UNUSED_RESULT
  3926. static basic_json from_bjdata(IteratorType first, IteratorType last,
  3927. const bool strict = true,
  3928. const bool allow_exceptions = true)
  3929. {
  3930. basic_json result;
  3931. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  3932. auto ia = detail::input_adapter(std::move(first), std::move(last));
  3933. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::bjdata).sax_parse(input_format_t::bjdata, &sdp, strict);
  3934. return res ? result : basic_json(value_t::discarded);
  3935. }
  3936. /// @brief create a JSON value from an input in BSON format
  3937. /// @sa https://json.nlohmann.me/api/basic_json/from_bson/
  3938. template<typename InputType>
  3939. JSON_HEDLEY_WARN_UNUSED_RESULT
  3940. static basic_json from_bson(InputType&& i,
  3941. const bool strict = true,
  3942. const bool allow_exceptions = true)
  3943. {
  3944. basic_json result;
  3945. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  3946. auto ia = detail::input_adapter(std::forward<InputType>(i));
  3947. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::bson).sax_parse(input_format_t::bson, &sdp, strict);
  3948. return res ? result : basic_json(value_t::discarded);
  3949. }
  3950. /// @brief create a JSON value from an input in BSON format
  3951. /// @sa https://json.nlohmann.me/api/basic_json/from_bson/
  3952. template<typename IteratorType>
  3953. JSON_HEDLEY_WARN_UNUSED_RESULT
  3954. static basic_json from_bson(IteratorType first, IteratorType last,
  3955. const bool strict = true,
  3956. const bool allow_exceptions = true)
  3957. {
  3958. basic_json result;
  3959. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  3960. auto ia = detail::input_adapter(std::move(first), std::move(last));
  3961. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::bson).sax_parse(input_format_t::bson, &sdp, strict);
  3962. return res ? result : basic_json(value_t::discarded);
  3963. }
  3964. template<typename T>
  3965. JSON_HEDLEY_WARN_UNUSED_RESULT
  3966. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len))
  3967. static basic_json from_bson(const T* ptr, std::size_t len,
  3968. const bool strict = true,
  3969. const bool allow_exceptions = true)
  3970. {
  3971. return from_bson(ptr, ptr + len, strict, allow_exceptions);
  3972. }
  3973. JSON_HEDLEY_WARN_UNUSED_RESULT
  3974. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len))
  3975. static basic_json from_bson(detail::span_input_adapter&& i,
  3976. const bool strict = true,
  3977. const bool allow_exceptions = true)
  3978. {
  3979. basic_json result;
  3980. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  3981. auto ia = i.get();
  3982. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  3983. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::bson).sax_parse(input_format_t::bson, &sdp, strict);
  3984. return res ? result : basic_json(value_t::discarded);
  3985. }
  3986. /// @}
  3987. //////////////////////////
  3988. // JSON Pointer support //
  3989. //////////////////////////
  3990. /// @name JSON Pointer functions
  3991. /// @{
  3992. /// @brief access specified element via JSON Pointer
  3993. /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
  3994. reference operator[](const json_pointer& ptr)
  3995. {
  3996. return ptr.get_unchecked(this);
  3997. }
  3998. template<typename BasicJsonType, detail::enable_if_t<detail::is_basic_json<BasicJsonType>::value, int> = 0>
  3999. JSON_HEDLEY_DEPRECATED_FOR(3.11.0, basic_json::json_pointer or nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens)
  4000. reference operator[](const ::nlohmann::json_pointer<BasicJsonType>& ptr)
  4001. {
  4002. return ptr.get_unchecked(this);
  4003. }
  4004. /// @brief access specified element via JSON Pointer
  4005. /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
  4006. const_reference operator[](const json_pointer& ptr) const
  4007. {
  4008. return ptr.get_unchecked(this);
  4009. }
  4010. template<typename BasicJsonType, detail::enable_if_t<detail::is_basic_json<BasicJsonType>::value, int> = 0>
  4011. JSON_HEDLEY_DEPRECATED_FOR(3.11.0, basic_json::json_pointer or nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens)
  4012. const_reference operator[](const ::nlohmann::json_pointer<BasicJsonType>& ptr) const
  4013. {
  4014. return ptr.get_unchecked(this);
  4015. }
  4016. /// @brief access specified element via JSON Pointer
  4017. /// @sa https://json.nlohmann.me/api/basic_json/at/
  4018. reference at(const json_pointer& ptr)
  4019. {
  4020. return ptr.get_checked(this);
  4021. }
  4022. template<typename BasicJsonType, detail::enable_if_t<detail::is_basic_json<BasicJsonType>::value, int> = 0>
  4023. JSON_HEDLEY_DEPRECATED_FOR(3.11.0, basic_json::json_pointer or nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens)
  4024. reference at(const ::nlohmann::json_pointer<BasicJsonType>& ptr)
  4025. {
  4026. return ptr.get_checked(this);
  4027. }
  4028. /// @brief access specified element via JSON Pointer
  4029. /// @sa https://json.nlohmann.me/api/basic_json/at/
  4030. const_reference at(const json_pointer& ptr) const
  4031. {
  4032. return ptr.get_checked(this);
  4033. }
  4034. template<typename BasicJsonType, detail::enable_if_t<detail::is_basic_json<BasicJsonType>::value, int> = 0>
  4035. JSON_HEDLEY_DEPRECATED_FOR(3.11.0, basic_json::json_pointer or nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens)
  4036. const_reference at(const ::nlohmann::json_pointer<BasicJsonType>& ptr) const
  4037. {
  4038. return ptr.get_checked(this);
  4039. }
  4040. /// @brief return flattened JSON value
  4041. /// @sa https://json.nlohmann.me/api/basic_json/flatten/
  4042. basic_json flatten() const
  4043. {
  4044. basic_json result(value_t::object);
  4045. json_pointer::flatten("", *this, result);
  4046. return result;
  4047. }
  4048. /// @brief unflatten a previously flattened JSON value
  4049. /// @sa https://json.nlohmann.me/api/basic_json/unflatten/
  4050. basic_json unflatten() const
  4051. {
  4052. return json_pointer::unflatten(*this);
  4053. }
  4054. /// @}
  4055. //////////////////////////
  4056. // JSON Patch functions //
  4057. //////////////////////////
  4058. /// @name JSON Patch functions
  4059. /// @{
  4060. /// @brief applies a JSON patch in-place without copying the object
  4061. /// @sa https://json.nlohmann.me/api/basic_json/patch/
  4062. void patch_inplace(const basic_json& json_patch)
  4063. {
  4064. basic_json& result = *this;
  4065. // the valid JSON Patch operations
  4066. enum class patch_operations {add, remove, replace, move, copy, test, invalid};
  4067. const auto get_op = [](const std::string & op)
  4068. {
  4069. if (op == "add")
  4070. {
  4071. return patch_operations::add;
  4072. }
  4073. if (op == "remove")
  4074. {
  4075. return patch_operations::remove;
  4076. }
  4077. if (op == "replace")
  4078. {
  4079. return patch_operations::replace;
  4080. }
  4081. if (op == "move")
  4082. {
  4083. return patch_operations::move;
  4084. }
  4085. if (op == "copy")
  4086. {
  4087. return patch_operations::copy;
  4088. }
  4089. if (op == "test")
  4090. {
  4091. return patch_operations::test;
  4092. }
  4093. return patch_operations::invalid;
  4094. };
  4095. // wrapper for "add" operation; add value at ptr
  4096. const auto operation_add = [&result](json_pointer & ptr, basic_json val)
  4097. {
  4098. // adding to the root of the target document means replacing it
  4099. if (ptr.empty())
  4100. {
  4101. result = val;
  4102. return;
  4103. }
  4104. // make sure the top element of the pointer exists
  4105. json_pointer const top_pointer = ptr.top();
  4106. if (top_pointer != ptr)
  4107. {
  4108. result.at(top_pointer);
  4109. }
  4110. // get reference to parent of JSON pointer ptr
  4111. const auto last_path = ptr.back();
  4112. ptr.pop_back();
  4113. // parent must exist when performing patch add per RFC6902 specs
  4114. basic_json& parent = result.at(ptr);
  4115. switch (parent.m_type)
  4116. {
  4117. case value_t::null:
  4118. case value_t::object:
  4119. {
  4120. // use operator[] to add value
  4121. parent[last_path] = val;
  4122. break;
  4123. }
  4124. case value_t::array:
  4125. {
  4126. if (last_path == "-")
  4127. {
  4128. // special case: append to back
  4129. parent.push_back(val);
  4130. }
  4131. else
  4132. {
  4133. const auto idx = json_pointer::template array_index<basic_json_t>(last_path);
  4134. if (JSON_HEDLEY_UNLIKELY(idx > parent.size()))
  4135. {
  4136. // avoid undefined behavior
  4137. JSON_THROW(out_of_range::create(401, detail::concat("array index ", std::to_string(idx), " is out of range"), &parent));
  4138. }
  4139. // default case: insert add offset
  4140. parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
  4141. }
  4142. break;
  4143. }
  4144. // if there exists a parent it cannot be primitive
  4145. case value_t::string: // LCOV_EXCL_LINE
  4146. case value_t::boolean: // LCOV_EXCL_LINE
  4147. case value_t::number_integer: // LCOV_EXCL_LINE
  4148. case value_t::number_unsigned: // LCOV_EXCL_LINE
  4149. case value_t::number_float: // LCOV_EXCL_LINE
  4150. case value_t::binary: // LCOV_EXCL_LINE
  4151. case value_t::discarded: // LCOV_EXCL_LINE
  4152. default: // LCOV_EXCL_LINE
  4153. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  4154. }
  4155. };
  4156. // wrapper for "remove" operation; remove value at ptr
  4157. const auto operation_remove = [this, &result](json_pointer & ptr)
  4158. {
  4159. // get reference to parent of JSON pointer ptr
  4160. const auto last_path = ptr.back();
  4161. ptr.pop_back();
  4162. basic_json& parent = result.at(ptr);
  4163. // remove child
  4164. if (parent.is_object())
  4165. {
  4166. // perform range check
  4167. auto it = parent.find(last_path);
  4168. if (JSON_HEDLEY_LIKELY(it != parent.end()))
  4169. {
  4170. parent.erase(it);
  4171. }
  4172. else
  4173. {
  4174. JSON_THROW(out_of_range::create(403, detail::concat("key '", last_path, "' not found"), this));
  4175. }
  4176. }
  4177. else if (parent.is_array())
  4178. {
  4179. // note erase performs range check
  4180. parent.erase(json_pointer::template array_index<basic_json_t>(last_path));
  4181. }
  4182. };
  4183. // type check: top level value must be an array
  4184. if (JSON_HEDLEY_UNLIKELY(!json_patch.is_array()))
  4185. {
  4186. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", &json_patch));
  4187. }
  4188. // iterate and apply the operations
  4189. for (const auto& val : json_patch)
  4190. {
  4191. // wrapper to get a value for an operation
  4192. const auto get_value = [&val](const std::string & op,
  4193. const std::string & member,
  4194. bool string_type) -> basic_json &
  4195. {
  4196. // find value
  4197. auto it = val.m_value.object->find(member);
  4198. // context-sensitive error message
  4199. const auto error_msg = (op == "op") ? "operation" : detail::concat("operation '", op, '\'');
  4200. // check if desired value is present
  4201. if (JSON_HEDLEY_UNLIKELY(it == val.m_value.object->end()))
  4202. {
  4203. // NOLINTNEXTLINE(performance-inefficient-string-concatenation)
  4204. JSON_THROW(parse_error::create(105, 0, detail::concat(error_msg, " must have member '", member, "'"), &val));
  4205. }
  4206. // check if result is of type string
  4207. if (JSON_HEDLEY_UNLIKELY(string_type && !it->second.is_string()))
  4208. {
  4209. // NOLINTNEXTLINE(performance-inefficient-string-concatenation)
  4210. JSON_THROW(parse_error::create(105, 0, detail::concat(error_msg, " must have string member '", member, "'"), &val));
  4211. }
  4212. // no error: return value
  4213. return it->second;
  4214. };
  4215. // type check: every element of the array must be an object
  4216. if (JSON_HEDLEY_UNLIKELY(!val.is_object()))
  4217. {
  4218. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", &val));
  4219. }
  4220. // collect mandatory members
  4221. const auto op = get_value("op", "op", true).template get<std::string>();
  4222. const auto path = get_value(op, "path", true).template get<std::string>();
  4223. json_pointer ptr(path);
  4224. switch (get_op(op))
  4225. {
  4226. case patch_operations::add:
  4227. {
  4228. operation_add(ptr, get_value("add", "value", false));
  4229. break;
  4230. }
  4231. case patch_operations::remove:
  4232. {
  4233. operation_remove(ptr);
  4234. break;
  4235. }
  4236. case patch_operations::replace:
  4237. {
  4238. // the "path" location must exist - use at()
  4239. result.at(ptr) = get_value("replace", "value", false);
  4240. break;
  4241. }
  4242. case patch_operations::move:
  4243. {
  4244. const auto from_path = get_value("move", "from", true).template get<std::string>();
  4245. json_pointer from_ptr(from_path);
  4246. // the "from" location must exist - use at()
  4247. basic_json const v = result.at(from_ptr);
  4248. // The move operation is functionally identical to a
  4249. // "remove" operation on the "from" location, followed
  4250. // immediately by an "add" operation at the target
  4251. // location with the value that was just removed.
  4252. operation_remove(from_ptr);
  4253. operation_add(ptr, v);
  4254. break;
  4255. }
  4256. case patch_operations::copy:
  4257. {
  4258. const auto from_path = get_value("copy", "from", true).template get<std::string>();
  4259. const json_pointer from_ptr(from_path);
  4260. // the "from" location must exist - use at()
  4261. basic_json const v = result.at(from_ptr);
  4262. // The copy is functionally identical to an "add"
  4263. // operation at the target location using the value
  4264. // specified in the "from" member.
  4265. operation_add(ptr, v);
  4266. break;
  4267. }
  4268. case patch_operations::test:
  4269. {
  4270. bool success = false;
  4271. JSON_TRY
  4272. {
  4273. // check if "value" matches the one at "path"
  4274. // the "path" location must exist - use at()
  4275. success = (result.at(ptr) == get_value("test", "value", false));
  4276. }
  4277. JSON_INTERNAL_CATCH (out_of_range&)
  4278. {
  4279. // ignore out of range errors: success remains false
  4280. }
  4281. // throw an exception if test fails
  4282. if (JSON_HEDLEY_UNLIKELY(!success))
  4283. {
  4284. JSON_THROW(other_error::create(501, detail::concat("unsuccessful: ", val.dump()), &val));
  4285. }
  4286. break;
  4287. }
  4288. case patch_operations::invalid:
  4289. default:
  4290. {
  4291. // op must be "add", "remove", "replace", "move", "copy", or
  4292. // "test"
  4293. JSON_THROW(parse_error::create(105, 0, detail::concat("operation value '", op, "' is invalid"), &val));
  4294. }
  4295. }
  4296. }
  4297. }
  4298. /// @brief applies a JSON patch to a copy of the current object
  4299. /// @sa https://json.nlohmann.me/api/basic_json/patch/
  4300. basic_json patch(const basic_json& json_patch) const
  4301. {
  4302. basic_json result = *this;
  4303. result.patch_inplace(json_patch);
  4304. return result;
  4305. }
  4306. /// @brief creates a diff as a JSON patch
  4307. /// @sa https://json.nlohmann.me/api/basic_json/diff/
  4308. JSON_HEDLEY_WARN_UNUSED_RESULT
  4309. static basic_json diff(const basic_json& source, const basic_json& target,
  4310. const std::string& path = "")
  4311. {
  4312. // the patch
  4313. basic_json result(value_t::array);
  4314. // if the values are the same, return empty patch
  4315. if (source == target)
  4316. {
  4317. return result;
  4318. }
  4319. if (source.type() != target.type())
  4320. {
  4321. // different types: replace value
  4322. result.push_back(
  4323. {
  4324. {"op", "replace"}, {"path", path}, {"value", target}
  4325. });
  4326. return result;
  4327. }
  4328. switch (source.type())
  4329. {
  4330. case value_t::array:
  4331. {
  4332. // first pass: traverse common elements
  4333. std::size_t i = 0;
  4334. while (i < source.size() && i < target.size())
  4335. {
  4336. // recursive call to compare array values at index i
  4337. auto temp_diff = diff(source[i], target[i], detail::concat(path, '/', std::to_string(i)));
  4338. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  4339. ++i;
  4340. }
  4341. // We now reached the end of at least one array
  4342. // in a second pass, traverse the remaining elements
  4343. // remove my remaining elements
  4344. const auto end_index = static_cast<difference_type>(result.size());
  4345. while (i < source.size())
  4346. {
  4347. // add operations in reverse order to avoid invalid
  4348. // indices
  4349. result.insert(result.begin() + end_index, object(
  4350. {
  4351. {"op", "remove"},
  4352. {"path", detail::concat(path, '/', std::to_string(i))}
  4353. }));
  4354. ++i;
  4355. }
  4356. // add other remaining elements
  4357. while (i < target.size())
  4358. {
  4359. result.push_back(
  4360. {
  4361. {"op", "add"},
  4362. {"path", detail::concat(path, "/-")},
  4363. {"value", target[i]}
  4364. });
  4365. ++i;
  4366. }
  4367. break;
  4368. }
  4369. case value_t::object:
  4370. {
  4371. // first pass: traverse this object's elements
  4372. for (auto it = source.cbegin(); it != source.cend(); ++it)
  4373. {
  4374. // escape the key name to be used in a JSON patch
  4375. const auto path_key = detail::concat(path, '/', detail::escape(it.key()));
  4376. if (target.find(it.key()) != target.end())
  4377. {
  4378. // recursive call to compare object values at key it
  4379. auto temp_diff = diff(it.value(), target[it.key()], path_key);
  4380. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  4381. }
  4382. else
  4383. {
  4384. // found a key that is not in o -> remove it
  4385. result.push_back(object(
  4386. {
  4387. {"op", "remove"}, {"path", path_key}
  4388. }));
  4389. }
  4390. }
  4391. // second pass: traverse other object's elements
  4392. for (auto it = target.cbegin(); it != target.cend(); ++it)
  4393. {
  4394. if (source.find(it.key()) == source.end())
  4395. {
  4396. // found a key that is not in this -> add it
  4397. const auto path_key = detail::concat(path, '/', detail::escape(it.key()));
  4398. result.push_back(
  4399. {
  4400. {"op", "add"}, {"path", path_key},
  4401. {"value", it.value()}
  4402. });
  4403. }
  4404. }
  4405. break;
  4406. }
  4407. case value_t::null:
  4408. case value_t::string:
  4409. case value_t::boolean:
  4410. case value_t::number_integer:
  4411. case value_t::number_unsigned:
  4412. case value_t::number_float:
  4413. case value_t::binary:
  4414. case value_t::discarded:
  4415. default:
  4416. {
  4417. // both primitive type: replace value
  4418. result.push_back(
  4419. {
  4420. {"op", "replace"}, {"path", path}, {"value", target}
  4421. });
  4422. break;
  4423. }
  4424. }
  4425. return result;
  4426. }
  4427. /// @}
  4428. ////////////////////////////////
  4429. // JSON Merge Patch functions //
  4430. ////////////////////////////////
  4431. /// @name JSON Merge Patch functions
  4432. /// @{
  4433. /// @brief applies a JSON Merge Patch
  4434. /// @sa https://json.nlohmann.me/api/basic_json/merge_patch/
  4435. void merge_patch(const basic_json& apply_patch)
  4436. {
  4437. if (apply_patch.is_object())
  4438. {
  4439. if (!is_object())
  4440. {
  4441. *this = object();
  4442. }
  4443. for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it)
  4444. {
  4445. if (it.value().is_null())
  4446. {
  4447. erase(it.key());
  4448. }
  4449. else
  4450. {
  4451. operator[](it.key()).merge_patch(it.value());
  4452. }
  4453. }
  4454. }
  4455. else
  4456. {
  4457. *this = apply_patch;
  4458. }
  4459. }
  4460. /// @}
  4461. };
  4462. /// @brief user-defined to_string function for JSON values
  4463. /// @sa https://json.nlohmann.me/api/basic_json/to_string/
  4464. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  4465. std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j)
  4466. {
  4467. return j.dump();
  4468. }
  4469. inline namespace literals
  4470. {
  4471. inline namespace json_literals
  4472. {
  4473. /// @brief user-defined string literal for JSON values
  4474. /// @sa https://json.nlohmann.me/api/basic_json/operator_literal_json/
  4475. JSON_HEDLEY_NON_NULL(1)
  4476. inline nlohmann::json operator "" _json(const char* s, std::size_t n)
  4477. {
  4478. return nlohmann::json::parse(s, s + n);
  4479. }
  4480. /// @brief user-defined string literal for JSON pointer
  4481. /// @sa https://json.nlohmann.me/api/basic_json/operator_literal_json_pointer/
  4482. JSON_HEDLEY_NON_NULL(1)
  4483. inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
  4484. {
  4485. return nlohmann::json::json_pointer(std::string(s, n));
  4486. }
  4487. } // namespace json_literals
  4488. } // namespace literals
  4489. NLOHMANN_JSON_NAMESPACE_END
  4490. ///////////////////////
  4491. // nonmember support //
  4492. ///////////////////////
  4493. namespace std // NOLINT(cert-dcl58-cpp)
  4494. {
  4495. /// @brief hash value for JSON objects
  4496. /// @sa https://json.nlohmann.me/api/basic_json/std_hash/
  4497. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  4498. struct hash<nlohmann::NLOHMANN_BASIC_JSON_TPL> // NOLINT(cert-dcl58-cpp)
  4499. {
  4500. std::size_t operator()(const nlohmann::NLOHMANN_BASIC_JSON_TPL& j) const
  4501. {
  4502. return nlohmann::detail::hash(j);
  4503. }
  4504. };
  4505. // specialization for std::less<value_t>
  4506. template<>
  4507. struct less< ::nlohmann::detail::value_t> // do not remove the space after '<', see https://github.com/nlohmann/json/pull/679
  4508. {
  4509. /*!
  4510. @brief compare two value_t enum values
  4511. @since version 3.0.0
  4512. */
  4513. bool operator()(::nlohmann::detail::value_t lhs,
  4514. ::nlohmann::detail::value_t rhs) const noexcept
  4515. {
  4516. #if JSON_HAS_THREE_WAY_COMPARISON
  4517. return std::is_lt(lhs <=> rhs); // *NOPAD*
  4518. #else
  4519. return ::nlohmann::detail::operator<(lhs, rhs);
  4520. #endif
  4521. }
  4522. };
  4523. // C++20 prohibit function specialization in the std namespace.
  4524. #ifndef JSON_HAS_CPP_20
  4525. /// @brief exchanges the values of two JSON objects
  4526. /// @sa https://json.nlohmann.me/api/basic_json/std_swap/
  4527. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  4528. inline void swap(nlohmann::NLOHMANN_BASIC_JSON_TPL& j1, nlohmann::NLOHMANN_BASIC_JSON_TPL& j2) noexcept( // NOLINT(readability-inconsistent-declaration-parameter-name, cert-dcl58-cpp)
  4529. is_nothrow_move_constructible<nlohmann::NLOHMANN_BASIC_JSON_TPL>::value&& // NOLINT(misc-redundant-expression)
  4530. is_nothrow_move_assignable<nlohmann::NLOHMANN_BASIC_JSON_TPL>::value)
  4531. {
  4532. j1.swap(j2);
  4533. }
  4534. #endif
  4535. } // namespace std
  4536. #if JSON_USE_GLOBAL_UDLS
  4537. using nlohmann::literals::json_literals::operator "" _json; // NOLINT(misc-unused-using-decls,google-global-names-in-headers)
  4538. using nlohmann::literals::json_literals::operator "" _json_pointer; //NOLINT(misc-unused-using-decls,google-global-names-in-headers)
  4539. #endif
  4540. #include <nlohmann/detail/macro_unscope.hpp>
  4541. #endif // INCLUDE_NLOHMANN_JSON_HPP_