json.hpp 310 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700
  1. /*
  2. __ _____ _____ _____
  3. __| | __| | | | JSON for Modern C++
  4. | | |__ | | | | | | version 3.7.3
  5. |_____|_____|_____|_|___| https://github.com/nlohmann/json
  6. Licensed under the MIT License <http://opensource.org/licenses/MIT>.
  7. SPDX-License-Identifier: MIT
  8. Copyright (c) 2013-2019 Niels Lohmann <http://nlohmann.me>.
  9. Permission is hereby granted, free of charge, to any person obtaining a copy
  10. of this software and associated documentation files (the "Software"), to deal
  11. in the Software without restriction, including without limitation the rights
  12. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. copies of the Software, and to permit persons to whom the Software is
  14. furnished to do so, subject to the following conditions:
  15. The above copyright notice and this permission notice shall be included in all
  16. copies or substantial portions of the Software.
  17. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. SOFTWARE.
  24. */
  25. #ifndef INCLUDE_NLOHMANN_JSON_HPP_
  26. #define INCLUDE_NLOHMANN_JSON_HPP_
  27. #define NLOHMANN_JSON_VERSION_MAJOR 3
  28. #define NLOHMANN_JSON_VERSION_MINOR 7
  29. #define NLOHMANN_JSON_VERSION_PATCH 3
  30. #include <algorithm> // all_of, find, for_each
  31. #include <cassert> // assert
  32. #include <cstddef> // nullptr_t, ptrdiff_t, size_t
  33. #include <functional> // hash, less
  34. #include <initializer_list> // initializer_list
  35. #include <iosfwd> // istream, ostream
  36. #include <iterator> // random_access_iterator_tag
  37. #include <memory> // unique_ptr
  38. #include <numeric> // accumulate
  39. #include <string> // string, stoi, to_string
  40. #include <utility> // declval, forward, move, pair, swap
  41. #include <vector> // vector
  42. #include <nlohmann/adl_serializer.hpp>
  43. #include <nlohmann/byte_container_with_subtype.hpp>
  44. #include <nlohmann/detail/boolean_operators.hpp>
  45. #include <nlohmann/detail/conversions/from_json.hpp>
  46. #include <nlohmann/detail/conversions/to_json.hpp>
  47. #include <nlohmann/detail/exceptions.hpp>
  48. #include <nlohmann/detail/input/binary_reader.hpp>
  49. #include <nlohmann/detail/input/input_adapters.hpp>
  50. #include <nlohmann/detail/input/lexer.hpp>
  51. #include <nlohmann/detail/input/parser.hpp>
  52. #include <nlohmann/detail/iterators/internal_iterator.hpp>
  53. #include <nlohmann/detail/iterators/iter_impl.hpp>
  54. #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  55. #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
  56. #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  57. #include <nlohmann/detail/json_pointer.hpp>
  58. #include <nlohmann/detail/json_ref.hpp>
  59. #include <nlohmann/detail/macro_scope.hpp>
  60. #include <nlohmann/detail/meta/cpp_future.hpp>
  61. #include <nlohmann/detail/meta/type_traits.hpp>
  62. #include <nlohmann/detail/output/binary_writer.hpp>
  63. #include <nlohmann/detail/output/output_adapters.hpp>
  64. #include <nlohmann/detail/output/serializer.hpp>
  65. #include <nlohmann/detail/value_t.hpp>
  66. #include <nlohmann/json_fwd.hpp>
  67. /*!
  68. @brief namespace for Niels Lohmann
  69. @see https://github.com/nlohmann
  70. @since version 1.0.0
  71. */
  72. namespace nlohmann
  73. {
  74. /*!
  75. @brief a class to store JSON values
  76. @tparam ObjectType type for JSON objects (`std::map` by default; will be used
  77. in @ref object_t)
  78. @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
  79. in @ref array_t)
  80. @tparam StringType type for JSON strings and object keys (`std::string` by
  81. default; will be used in @ref string_t)
  82. @tparam BooleanType type for JSON booleans (`bool` by default; will be used
  83. in @ref boolean_t)
  84. @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
  85. default; will be used in @ref number_integer_t)
  86. @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
  87. `uint64_t` by default; will be used in @ref number_unsigned_t)
  88. @tparam NumberFloatType type for JSON floating-point numbers (`double` by
  89. default; will be used in @ref number_float_t)
  90. @tparam BinaryType type for packed binary data for compatibility with binary
  91. serialization formats (`std::vector<std::uint8_t>` by default; will be used in
  92. @ref binary_t)
  93. @tparam AllocatorType type of the allocator to use (`std::allocator` by
  94. default)
  95. @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
  96. and `from_json()` (@ref adl_serializer by default)
  97. @requirement The class satisfies the following concept requirements:
  98. - Basic
  99. - [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible):
  100. JSON values can be default constructed. The result will be a JSON null
  101. value.
  102. - [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible):
  103. A JSON value can be constructed from an rvalue argument.
  104. - [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible):
  105. A JSON value can be copy-constructed from an lvalue expression.
  106. - [MoveAssignable](https://en.cppreference.com/w/cpp/named_req/MoveAssignable):
  107. A JSON value van be assigned from an rvalue argument.
  108. - [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable):
  109. A JSON value can be copy-assigned from an lvalue expression.
  110. - [Destructible](https://en.cppreference.com/w/cpp/named_req/Destructible):
  111. JSON values can be destructed.
  112. - Layout
  113. - [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType):
  114. JSON values have
  115. [standard layout](https://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
  116. All non-static data members are private and standard layout types, the
  117. class has no virtual functions or (virtual) base classes.
  118. - Library-wide
  119. - [EqualityComparable](https://en.cppreference.com/w/cpp/named_req/EqualityComparable):
  120. JSON values can be compared with `==`, see @ref
  121. operator==(const_reference,const_reference).
  122. - [LessThanComparable](https://en.cppreference.com/w/cpp/named_req/LessThanComparable):
  123. JSON values can be compared with `<`, see @ref
  124. operator<(const_reference,const_reference).
  125. - [Swappable](https://en.cppreference.com/w/cpp/named_req/Swappable):
  126. Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
  127. other compatible types, using unqualified function call @ref swap().
  128. - [NullablePointer](https://en.cppreference.com/w/cpp/named_req/NullablePointer):
  129. JSON values can be compared against `std::nullptr_t` objects which are used
  130. to model the `null` value.
  131. - Container
  132. - [Container](https://en.cppreference.com/w/cpp/named_req/Container):
  133. JSON values can be used like STL containers and provide iterator access.
  134. - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer);
  135. JSON values can be used like STL containers and provide reverse iterator
  136. access.
  137. @invariant The member variables @a m_value and @a m_type have the following
  138. relationship:
  139. - If `m_type == value_t::object`, then `m_value.object != nullptr`.
  140. - If `m_type == value_t::array`, then `m_value.array != nullptr`.
  141. - If `m_type == value_t::string`, then `m_value.string != nullptr`.
  142. The invariants are checked by member function assert_invariant().
  143. @internal
  144. @note ObjectType trick from https://stackoverflow.com/a/9860911
  145. @endinternal
  146. @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
  147. Format](http://rfc7159.net/rfc7159)
  148. @since version 1.0.0
  149. @nosubgrouping
  150. */
  151. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  152. class basic_json
  153. {
  154. private:
  155. template<detail::value_t> friend struct detail::external_constructor;
  156. friend ::nlohmann::json_pointer<basic_json>;
  157. template<typename BasicJsonType, typename InputType>
  158. friend class ::nlohmann::detail::parser;
  159. friend ::nlohmann::detail::serializer<basic_json>;
  160. template<typename BasicJsonType>
  161. friend class ::nlohmann::detail::iter_impl;
  162. template<typename BasicJsonType, typename CharType>
  163. friend class ::nlohmann::detail::binary_writer;
  164. template<typename BasicJsonType, typename InputType, typename SAX>
  165. friend class ::nlohmann::detail::binary_reader;
  166. template<typename BasicJsonType>
  167. friend class ::nlohmann::detail::json_sax_dom_parser;
  168. template<typename BasicJsonType>
  169. friend class ::nlohmann::detail::json_sax_dom_callback_parser;
  170. /// workaround type for MSVC
  171. using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
  172. // convenience aliases for types residing in namespace detail;
  173. using lexer = ::nlohmann::detail::lexer_base<basic_json>;
  174. template<typename InputAdapterType>
  175. static ::nlohmann::detail::parser<basic_json, InputAdapterType> parser(
  176. InputAdapterType adapter,
  177. detail::parser_callback_t<basic_json>cb = nullptr,
  178. bool allow_exceptions = true
  179. )
  180. {
  181. return ::nlohmann::detail::parser<basic_json, InputAdapterType>(std::move(adapter), std::move(cb), allow_exceptions);
  182. }
  183. using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
  184. template<typename BasicJsonType>
  185. using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
  186. template<typename BasicJsonType>
  187. using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
  188. template<typename Iterator>
  189. using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
  190. template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
  191. template<typename CharType>
  192. using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
  193. template<typename InputType>
  194. using binary_reader = ::nlohmann::detail::binary_reader<basic_json, InputType>;
  195. template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
  196. using serializer = ::nlohmann::detail::serializer<basic_json>;
  197. public:
  198. using value_t = detail::value_t;
  199. /// JSON Pointer, see @ref nlohmann::json_pointer
  200. using json_pointer = ::nlohmann::json_pointer<basic_json>;
  201. template<typename T, typename SFINAE>
  202. using json_serializer = JSONSerializer<T, SFINAE>;
  203. /// how to treat decoding errors
  204. using error_handler_t = detail::error_handler_t;
  205. /// helper type for initializer lists of basic_json values
  206. using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
  207. using input_format_t = detail::input_format_t;
  208. /// SAX interface type, see @ref nlohmann::json_sax
  209. using json_sax_t = json_sax<basic_json>;
  210. ////////////////
  211. // exceptions //
  212. ////////////////
  213. /// @name exceptions
  214. /// Classes to implement user-defined exceptions.
  215. /// @{
  216. /// @copydoc detail::exception
  217. using exception = detail::exception;
  218. /// @copydoc detail::parse_error
  219. using parse_error = detail::parse_error;
  220. /// @copydoc detail::invalid_iterator
  221. using invalid_iterator = detail::invalid_iterator;
  222. /// @copydoc detail::type_error
  223. using type_error = detail::type_error;
  224. /// @copydoc detail::out_of_range
  225. using out_of_range = detail::out_of_range;
  226. /// @copydoc detail::other_error
  227. using other_error = detail::other_error;
  228. /// @}
  229. /////////////////////
  230. // container types //
  231. /////////////////////
  232. /// @name container types
  233. /// The canonic container types to use @ref basic_json like any other STL
  234. /// container.
  235. /// @{
  236. /// the type of elements in a basic_json container
  237. using value_type = basic_json;
  238. /// the type of an element reference
  239. using reference = value_type&;
  240. /// the type of an element const reference
  241. using const_reference = const value_type&;
  242. /// a type to represent differences between iterators
  243. using difference_type = std::ptrdiff_t;
  244. /// a type to represent container sizes
  245. using size_type = std::size_t;
  246. /// the allocator type
  247. using allocator_type = AllocatorType<basic_json>;
  248. /// the type of an element pointer
  249. using pointer = typename std::allocator_traits<allocator_type>::pointer;
  250. /// the type of an element const pointer
  251. using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
  252. /// an iterator for a basic_json container
  253. using iterator = iter_impl<basic_json>;
  254. /// a const iterator for a basic_json container
  255. using const_iterator = iter_impl<const basic_json>;
  256. /// a reverse iterator for a basic_json container
  257. using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
  258. /// a const reverse iterator for a basic_json container
  259. using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
  260. /// @}
  261. /*!
  262. @brief returns the allocator associated with the container
  263. */
  264. static allocator_type get_allocator()
  265. {
  266. return allocator_type();
  267. }
  268. /*!
  269. @brief returns version information on the library
  270. This function returns a JSON object with information about the library,
  271. including the version number and information on the platform and compiler.
  272. @return JSON object holding version information
  273. key | description
  274. ----------- | ---------------
  275. `compiler` | Information on the used compiler. It is an object with the following keys: `c++` (the used C++ standard), `family` (the compiler family; possible values are `clang`, `icc`, `gcc`, `ilecpp`, `msvc`, `pgcpp`, `sunpro`, and `unknown`), and `version` (the compiler version).
  276. `copyright` | The copyright line for the library as string.
  277. `name` | The name of the library as string.
  278. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
  279. `url` | The URL of the project as string.
  280. `version` | The version of the library. It is an object with the following keys: `major`, `minor`, and `patch` as defined by [Semantic Versioning](http://semver.org), and `string` (the version string).
  281. @liveexample{The following code shows an example output of the `meta()`
  282. function.,meta}
  283. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  284. changes to any JSON value.
  285. @complexity Constant.
  286. @since 2.1.0
  287. */
  288. JSON_HEDLEY_WARN_UNUSED_RESULT
  289. static basic_json meta()
  290. {
  291. basic_json result;
  292. result["copyright"] = "(C) 2013-2017 Niels Lohmann";
  293. result["name"] = "JSON for Modern C++";
  294. result["url"] = "https://github.com/nlohmann/json";
  295. result["version"]["string"] =
  296. std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." +
  297. std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." +
  298. std::to_string(NLOHMANN_JSON_VERSION_PATCH);
  299. result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR;
  300. result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR;
  301. result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH;
  302. #ifdef _WIN32
  303. result["platform"] = "win32";
  304. #elif defined __linux__
  305. result["platform"] = "linux";
  306. #elif defined __APPLE__
  307. result["platform"] = "apple";
  308. #elif defined __unix__
  309. result["platform"] = "unix";
  310. #else
  311. result["platform"] = "unknown";
  312. #endif
  313. #if defined(__ICC) || defined(__INTEL_COMPILER)
  314. result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
  315. #elif defined(__clang__)
  316. result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
  317. #elif defined(__GNUC__) || defined(__GNUG__)
  318. result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
  319. #elif defined(__HP_cc) || defined(__HP_aCC)
  320. result["compiler"] = "hp"
  321. #elif defined(__IBMCPP__)
  322. result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
  323. #elif defined(_MSC_VER)
  324. result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
  325. #elif defined(__PGI)
  326. result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
  327. #elif defined(__SUNPRO_CC)
  328. result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
  329. #else
  330. result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
  331. #endif
  332. #ifdef __cplusplus
  333. result["compiler"]["c++"] = std::to_string(__cplusplus);
  334. #else
  335. result["compiler"]["c++"] = "unknown";
  336. #endif
  337. return result;
  338. }
  339. ///////////////////////////
  340. // JSON value data types //
  341. ///////////////////////////
  342. /// @name JSON value data types
  343. /// The data types to store a JSON value. These types are derived from
  344. /// the template arguments passed to class @ref basic_json.
  345. /// @{
  346. #if defined(JSON_HAS_CPP_14)
  347. // Use transparent comparator if possible, combined with perfect forwarding
  348. // on find() and count() calls prevents unnecessary string construction.
  349. using object_comparator_t = std::less<>;
  350. #else
  351. using object_comparator_t = std::less<StringType>;
  352. #endif
  353. /*!
  354. @brief a type for an object
  355. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
  356. > An object is an unordered collection of zero or more name/value pairs,
  357. > where a name is a string and a value is a string, number, boolean, null,
  358. > object, or array.
  359. To store objects in C++, a type is defined by the template parameters
  360. described below.
  361. @tparam ObjectType the container to store objects (e.g., `std::map` or
  362. `std::unordered_map`)
  363. @tparam StringType the type of the keys or names (e.g., `std::string`).
  364. The comparison function `std::less<StringType>` is used to order elements
  365. inside the container.
  366. @tparam AllocatorType the allocator to use for objects (e.g.,
  367. `std::allocator`)
  368. #### Default type
  369. With the default values for @a ObjectType (`std::map`), @a StringType
  370. (`std::string`), and @a AllocatorType (`std::allocator`), the default
  371. value for @a object_t is:
  372. @code {.cpp}
  373. std::map<
  374. std::string, // key_type
  375. basic_json, // value_type
  376. std::less<std::string>, // key_compare
  377. std::allocator<std::pair<const std::string, basic_json>> // allocator_type
  378. >
  379. @endcode
  380. #### Behavior
  381. The choice of @a object_t influences the behavior of the JSON class. With
  382. the default type, objects have the following behavior:
  383. - When all names are unique, objects will be interoperable in the sense
  384. that all software implementations receiving that object will agree on
  385. the name-value mappings.
  386. - When the names within an object are not unique, it is unspecified which
  387. one of the values for a given key will be chosen. For instance,
  388. `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or
  389. `{"key": 2}`.
  390. - Internally, name/value pairs are stored in lexicographical order of the
  391. names. Objects will also be serialized (see @ref dump) in this order.
  392. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
  393. and serialized as `{"a": 2, "b": 1}`.
  394. - When comparing objects, the order of the name/value pairs is irrelevant.
  395. This makes objects interoperable in the sense that they will not be
  396. affected by these differences. For instance, `{"b": 1, "a": 2}` and
  397. `{"a": 2, "b": 1}` will be treated as equal.
  398. #### Limits
  399. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  400. > An implementation may set limits on the maximum depth of nesting.
  401. In this class, the object's limit of nesting is not explicitly constrained.
  402. However, a maximum depth of nesting may be introduced by the compiler or
  403. runtime environment. A theoretical limit can be queried by calling the
  404. @ref max_size function of a JSON object.
  405. #### Storage
  406. Objects are stored as pointers in a @ref basic_json type. That is, for any
  407. access to object values, a pointer of type `object_t*` must be
  408. dereferenced.
  409. @sa @ref array_t -- type for an array value
  410. @since version 1.0.0
  411. @note The order name/value pairs are added to the object is *not*
  412. preserved by the library. Therefore, iterating an object may return
  413. name/value pairs in a different order than they were originally stored. In
  414. fact, keys will be traversed in alphabetical order as `std::map` with
  415. `std::less` is used by default. Please note this behavior conforms to [RFC
  416. 7159](http://rfc7159.net/rfc7159), because any order implements the
  417. specified "unordered" nature of JSON objects.
  418. */
  419. using object_t = ObjectType<StringType,
  420. basic_json,
  421. object_comparator_t,
  422. AllocatorType<std::pair<const StringType,
  423. basic_json>>>;
  424. /*!
  425. @brief a type for an array
  426. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
  427. > An array is an ordered sequence of zero or more values.
  428. To store objects in C++, a type is defined by the template parameters
  429. explained below.
  430. @tparam ArrayType container type to store arrays (e.g., `std::vector` or
  431. `std::list`)
  432. @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
  433. #### Default type
  434. With the default values for @a ArrayType (`std::vector`) and @a
  435. AllocatorType (`std::allocator`), the default value for @a array_t is:
  436. @code {.cpp}
  437. std::vector<
  438. basic_json, // value_type
  439. std::allocator<basic_json> // allocator_type
  440. >
  441. @endcode
  442. #### Limits
  443. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  444. > An implementation may set limits on the maximum depth of nesting.
  445. In this class, the array's limit of nesting is not explicitly constrained.
  446. However, a maximum depth of nesting may be introduced by the compiler or
  447. runtime environment. A theoretical limit can be queried by calling the
  448. @ref max_size function of a JSON array.
  449. #### Storage
  450. Arrays are stored as pointers in a @ref basic_json type. That is, for any
  451. access to array values, a pointer of type `array_t*` must be dereferenced.
  452. @sa @ref object_t -- type for an object value
  453. @since version 1.0.0
  454. */
  455. using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
  456. /*!
  457. @brief a type for a string
  458. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
  459. > A string is a sequence of zero or more Unicode characters.
  460. To store objects in C++, a type is defined by the template parameter
  461. described below. Unicode values are split by the JSON class into
  462. byte-sized characters during deserialization.
  463. @tparam StringType the container to store strings (e.g., `std::string`).
  464. Note this container is used for keys/names in objects, see @ref object_t.
  465. #### Default type
  466. With the default values for @a StringType (`std::string`), the default
  467. value for @a string_t is:
  468. @code {.cpp}
  469. std::string
  470. @endcode
  471. #### Encoding
  472. Strings are stored in UTF-8 encoding. Therefore, functions like
  473. `std::string::size()` or `std::string::length()` return the number of
  474. bytes in the string rather than the number of characters or glyphs.
  475. #### String comparison
  476. [RFC 7159](http://rfc7159.net/rfc7159) states:
  477. > Software implementations are typically required to test names of object
  478. > members for equality. Implementations that transform the textual
  479. > representation into sequences of Unicode code units and then perform the
  480. > comparison numerically, code unit by code unit, are interoperable in the
  481. > sense that implementations will agree in all cases on equality or
  482. > inequality of two strings. For example, implementations that compare
  483. > strings with escaped characters unconverted may incorrectly find that
  484. > `"a\\b"` and `"a\u005Cb"` are not equal.
  485. This implementation is interoperable as it does compare strings code unit
  486. by code unit.
  487. #### Storage
  488. String values are stored as pointers in a @ref basic_json type. That is,
  489. for any access to string values, a pointer of type `string_t*` must be
  490. dereferenced.
  491. @since version 1.0.0
  492. */
  493. using string_t = StringType;
  494. /*!
  495. @brief a type for a boolean
  496. [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
  497. type which differentiates the two literals `true` and `false`.
  498. To store objects in C++, a type is defined by the template parameter @a
  499. BooleanType which chooses the type to use.
  500. #### Default type
  501. With the default values for @a BooleanType (`bool`), the default value for
  502. @a boolean_t is:
  503. @code {.cpp}
  504. bool
  505. @endcode
  506. #### Storage
  507. Boolean values are stored directly inside a @ref basic_json type.
  508. @since version 1.0.0
  509. */
  510. using boolean_t = BooleanType;
  511. /*!
  512. @brief a type for a number (integer)
  513. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  514. > The representation of numbers is similar to that used in most
  515. > programming languages. A number is represented in base 10 using decimal
  516. > digits. It contains an integer component that may be prefixed with an
  517. > optional minus sign, which may be followed by a fraction part and/or an
  518. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  519. > cannot be represented in the grammar below (such as Infinity and NaN)
  520. > are not permitted.
  521. This description includes both integer and floating-point numbers.
  522. However, C++ allows more precise storage if it is known whether the number
  523. is a signed integer, an unsigned integer or a floating-point number.
  524. Therefore, three different types, @ref number_integer_t, @ref
  525. number_unsigned_t and @ref number_float_t are used.
  526. To store integer numbers in C++, a type is defined by the template
  527. parameter @a NumberIntegerType which chooses the type to use.
  528. #### Default type
  529. With the default values for @a NumberIntegerType (`int64_t`), the default
  530. value for @a number_integer_t is:
  531. @code {.cpp}
  532. int64_t
  533. @endcode
  534. #### Default behavior
  535. - The restrictions about leading zeros is not enforced in C++. Instead,
  536. leading zeros in integer literals lead to an interpretation as octal
  537. number. Internally, the value will be stored as decimal number. For
  538. instance, the C++ integer literal `010` will be serialized to `8`.
  539. During deserialization, leading zeros yield an error.
  540. - Not-a-number (NaN) values will be serialized to `null`.
  541. #### Limits
  542. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  543. > An implementation may set limits on the range and precision of numbers.
  544. When the default type is used, the maximal integer number that can be
  545. stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
  546. that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
  547. that are out of range will yield over/underflow when used in a
  548. constructor. During deserialization, too large or small integer numbers
  549. will be automatically be stored as @ref number_unsigned_t or @ref
  550. number_float_t.
  551. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  552. > Note that when such software is used, numbers that are integers and are
  553. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  554. > that implementations will agree exactly on their numeric values.
  555. As this range is a subrange of the exactly supported range [INT64_MIN,
  556. INT64_MAX], this class's integer type is interoperable.
  557. #### Storage
  558. Integer number values are stored directly inside a @ref basic_json type.
  559. @sa @ref number_float_t -- type for number values (floating-point)
  560. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  561. @since version 1.0.0
  562. */
  563. using number_integer_t = NumberIntegerType;
  564. /*!
  565. @brief a type for a number (unsigned)
  566. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  567. > The representation of numbers is similar to that used in most
  568. > programming languages. A number is represented in base 10 using decimal
  569. > digits. It contains an integer component that may be prefixed with an
  570. > optional minus sign, which may be followed by a fraction part and/or an
  571. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  572. > cannot be represented in the grammar below (such as Infinity and NaN)
  573. > are not permitted.
  574. This description includes both integer and floating-point numbers.
  575. However, C++ allows more precise storage if it is known whether the number
  576. is a signed integer, an unsigned integer or a floating-point number.
  577. Therefore, three different types, @ref number_integer_t, @ref
  578. number_unsigned_t and @ref number_float_t are used.
  579. To store unsigned integer numbers in C++, a type is defined by the
  580. template parameter @a NumberUnsignedType which chooses the type to use.
  581. #### Default type
  582. With the default values for @a NumberUnsignedType (`uint64_t`), the
  583. default value for @a number_unsigned_t is:
  584. @code {.cpp}
  585. uint64_t
  586. @endcode
  587. #### Default behavior
  588. - The restrictions about leading zeros is not enforced in C++. Instead,
  589. leading zeros in integer literals lead to an interpretation as octal
  590. number. Internally, the value will be stored as decimal number. For
  591. instance, the C++ integer literal `010` will be serialized to `8`.
  592. During deserialization, leading zeros yield an error.
  593. - Not-a-number (NaN) values will be serialized to `null`.
  594. #### Limits
  595. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  596. > An implementation may set limits on the range and precision of numbers.
  597. When the default type is used, the maximal integer number that can be
  598. stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
  599. number that can be stored is `0`. Integer numbers that are out of range
  600. will yield over/underflow when used in a constructor. During
  601. deserialization, too large or small integer numbers will be automatically
  602. be stored as @ref number_integer_t or @ref number_float_t.
  603. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  604. > Note that when such software is used, numbers that are integers and are
  605. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  606. > that implementations will agree exactly on their numeric values.
  607. As this range is a subrange (when considered in conjunction with the
  608. number_integer_t type) of the exactly supported range [0, UINT64_MAX],
  609. this class's integer type is interoperable.
  610. #### Storage
  611. Integer number values are stored directly inside a @ref basic_json type.
  612. @sa @ref number_float_t -- type for number values (floating-point)
  613. @sa @ref number_integer_t -- type for number values (integer)
  614. @since version 2.0.0
  615. */
  616. using number_unsigned_t = NumberUnsignedType;
  617. /*!
  618. @brief a type for a number (floating-point)
  619. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  620. > The representation of numbers is similar to that used in most
  621. > programming languages. A number is represented in base 10 using decimal
  622. > digits. It contains an integer component that may be prefixed with an
  623. > optional minus sign, which may be followed by a fraction part and/or an
  624. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  625. > cannot be represented in the grammar below (such as Infinity and NaN)
  626. > are not permitted.
  627. This description includes both integer and floating-point numbers.
  628. However, C++ allows more precise storage if it is known whether the number
  629. is a signed integer, an unsigned integer or a floating-point number.
  630. Therefore, three different types, @ref number_integer_t, @ref
  631. number_unsigned_t and @ref number_float_t are used.
  632. To store floating-point numbers in C++, a type is defined by the template
  633. parameter @a NumberFloatType which chooses the type to use.
  634. #### Default type
  635. With the default values for @a NumberFloatType (`double`), the default
  636. value for @a number_float_t is:
  637. @code {.cpp}
  638. double
  639. @endcode
  640. #### Default behavior
  641. - The restrictions about leading zeros is not enforced in C++. Instead,
  642. leading zeros in floating-point literals will be ignored. Internally,
  643. the value will be stored as decimal number. For instance, the C++
  644. floating-point literal `01.2` will be serialized to `1.2`. During
  645. deserialization, leading zeros yield an error.
  646. - Not-a-number (NaN) values will be serialized to `null`.
  647. #### Limits
  648. [RFC 7159](http://rfc7159.net/rfc7159) states:
  649. > This specification allows implementations to set limits on the range and
  650. > precision of numbers accepted. Since software that implements IEEE
  651. > 754-2008 binary64 (double precision) numbers is generally available and
  652. > widely used, good interoperability can be achieved by implementations
  653. > that expect no more precision or range than these provide, in the sense
  654. > that implementations will approximate JSON numbers within the expected
  655. > precision.
  656. This implementation does exactly follow this approach, as it uses double
  657. precision floating-point numbers. Note values smaller than
  658. `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
  659. will be stored as NaN internally and be serialized to `null`.
  660. #### Storage
  661. Floating-point number values are stored directly inside a @ref basic_json
  662. type.
  663. @sa @ref number_integer_t -- type for number values (integer)
  664. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  665. @since version 1.0.0
  666. */
  667. using number_float_t = NumberFloatType;
  668. /*!
  669. @brief a type for a packed binary type
  670. This type is a type designed to carry binary data that appears in various
  671. serialized formats, such as CBOR's Major Type 2, MessagePack's bin, and
  672. BSON's generic binary subtype. This type is NOT a part of standard JSON and
  673. exists solely for compatibility with these binary types. As such, it is
  674. simply defined as an ordered sequence of zero or more byte values.
  675. Additionally, as an implementation detail, the subtype of the binary data is
  676. carried around as a `std::uint8_t`, which is compatible with both of the
  677. binary data formats that use binary subtyping, (though the specific
  678. numbering is incompatible with each other, and it is up to the user to
  679. translate between them).
  680. [CBOR's RFC 7049](https://tools.ietf.org/html/rfc7049) describes this type
  681. as:
  682. > Major type 2: a byte string. The string's length in bytes is represented
  683. > following the rules for positive integers (major type 0).
  684. [MessagePack's documentation on the bin type
  685. family](https://github.com/msgpack/msgpack/blob/master/spec.md#bin-format-family)
  686. describes this type as:
  687. > Bin format family stores an byte array in 2, 3, or 5 bytes of extra bytes
  688. > in addition to the size of the byte array.
  689. [BSON's specifications](http://bsonspec.org/spec.html) describe several
  690. binary types; however, this type is intended to represent the generic binary
  691. type which has the description:
  692. > Generic binary subtype - This is the most commonly used binary subtype and
  693. > should be the 'default' for drivers and tools.
  694. None of these impose any limitations on the internal representation other
  695. than the basic unit of storage be some type of array whose parts are
  696. decomposable into bytes.
  697. The default representation of this binary format is a
  698. `std::vector<std::uint8_t>`, which is a very common way to represent a byte
  699. array in modern C++.
  700. #### Default type
  701. The default values for @a BinaryType is `std::vector<std::uint8_t>`
  702. #### Storage
  703. Binary Arrays are stored as pointers in a @ref basic_json type. That is,
  704. for any access to array values, a pointer of the type `binary_t*` must be
  705. dereferenced.
  706. #### Notes on subtypes
  707. - CBOR
  708. - Binary values are represented as byte strings. No subtypes are
  709. supported and will be ignored when CBOR is written.
  710. - MessagePack
  711. - If a subtype is given and the binary array contains exactly 1, 2, 4, 8,
  712. or 16 elements, the fixext family (fixext1, fixext2, fixext4, fixext8)
  713. is used. For other sizes, the ext family (ext8, ext16, ext32) is used.
  714. The subtype is then added as singed 8-bit integer.
  715. - If no subtype is given, the bin family (bin8, bin16, bin32) is used.
  716. - BSON
  717. - If a subtype is given, it is used and added as unsigned 8-bit integer.
  718. - If no subtype is given, the generic binary subtype 0x00 is used.
  719. @sa @ref binary -- create a binary array
  720. @since version 3.8.0
  721. */
  722. using binary_t = nlohmann::byte_container_with_subtype<BinaryType>;
  723. /// @}
  724. private:
  725. /// helper for exception-safe object creation
  726. template<typename T, typename... Args>
  727. JSON_HEDLEY_RETURNS_NON_NULL
  728. static T* create(Args&& ... args)
  729. {
  730. AllocatorType<T> alloc;
  731. using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
  732. auto deleter = [&](T * object)
  733. {
  734. AllocatorTraits::deallocate(alloc, object, 1);
  735. };
  736. std::unique_ptr<T, decltype(deleter)> object(AllocatorTraits::allocate(alloc, 1), deleter);
  737. AllocatorTraits::construct(alloc, object.get(), std::forward<Args>(args)...);
  738. assert(object != nullptr);
  739. return object.release();
  740. }
  741. ////////////////////////
  742. // JSON value storage //
  743. ////////////////////////
  744. /*!
  745. @brief a JSON value
  746. The actual storage for a JSON value of the @ref basic_json class. This
  747. union combines the different storage types for the JSON value types
  748. defined in @ref value_t.
  749. JSON type | value_t type | used type
  750. --------- | --------------- | ------------------------
  751. object | object | pointer to @ref object_t
  752. array | array | pointer to @ref array_t
  753. string | string | pointer to @ref string_t
  754. boolean | boolean | @ref boolean_t
  755. number | number_integer | @ref number_integer_t
  756. number | number_unsigned | @ref number_unsigned_t
  757. number | number_float | @ref number_float_t
  758. binary | binary | pointer to @ref binary_t
  759. null | null | *no value is stored*
  760. @note Variable-length types (objects, arrays, and strings) are stored as
  761. pointers. The size of the union should not exceed 64 bits if the default
  762. value types are used.
  763. @since version 1.0.0
  764. */
  765. union json_value
  766. {
  767. /// object (stored with pointer to save storage)
  768. object_t* object;
  769. /// array (stored with pointer to save storage)
  770. array_t* array;
  771. /// string (stored with pointer to save storage)
  772. string_t* string;
  773. /// binary (stored with pointer to save storage)
  774. binary_t* binary;
  775. /// boolean
  776. boolean_t boolean;
  777. /// number (integer)
  778. number_integer_t number_integer;
  779. /// number (unsigned integer)
  780. number_unsigned_t number_unsigned;
  781. /// number (floating-point)
  782. number_float_t number_float;
  783. /// default constructor (for null values)
  784. json_value() = default;
  785. /// constructor for booleans
  786. json_value(boolean_t v) noexcept : boolean(v) {}
  787. /// constructor for numbers (integer)
  788. json_value(number_integer_t v) noexcept : number_integer(v) {}
  789. /// constructor for numbers (unsigned)
  790. json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
  791. /// constructor for numbers (floating-point)
  792. json_value(number_float_t v) noexcept : number_float(v) {}
  793. /// constructor for empty values of a given type
  794. json_value(value_t t)
  795. {
  796. switch (t)
  797. {
  798. case value_t::object:
  799. {
  800. object = create<object_t>();
  801. break;
  802. }
  803. case value_t::array:
  804. {
  805. array = create<array_t>();
  806. break;
  807. }
  808. case value_t::string:
  809. {
  810. string = create<string_t>("");
  811. break;
  812. }
  813. case value_t::binary:
  814. {
  815. binary = create<binary_t>();
  816. break;
  817. }
  818. case value_t::boolean:
  819. {
  820. boolean = boolean_t(false);
  821. break;
  822. }
  823. case value_t::number_integer:
  824. {
  825. number_integer = number_integer_t(0);
  826. break;
  827. }
  828. case value_t::number_unsigned:
  829. {
  830. number_unsigned = number_unsigned_t(0);
  831. break;
  832. }
  833. case value_t::number_float:
  834. {
  835. number_float = number_float_t(0.0);
  836. break;
  837. }
  838. case value_t::null:
  839. {
  840. object = nullptr; // silence warning, see #821
  841. break;
  842. }
  843. default:
  844. {
  845. object = nullptr; // silence warning, see #821
  846. if (JSON_HEDLEY_UNLIKELY(t == value_t::null))
  847. {
  848. JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.7.3")); // LCOV_EXCL_LINE
  849. }
  850. break;
  851. }
  852. }
  853. }
  854. /// constructor for strings
  855. json_value(const string_t& value)
  856. {
  857. string = create<string_t>(value);
  858. }
  859. /// constructor for rvalue strings
  860. json_value(string_t&& value)
  861. {
  862. string = create<string_t>(std::move(value));
  863. }
  864. /// constructor for objects
  865. json_value(const object_t& value)
  866. {
  867. object = create<object_t>(value);
  868. }
  869. /// constructor for rvalue objects
  870. json_value(object_t&& value)
  871. {
  872. object = create<object_t>(std::move(value));
  873. }
  874. /// constructor for arrays
  875. json_value(const array_t& value)
  876. {
  877. array = create<array_t>(value);
  878. }
  879. /// constructor for rvalue arrays
  880. json_value(array_t&& value)
  881. {
  882. array = create<array_t>(std::move(value));
  883. }
  884. /// constructor for binary arrays
  885. json_value(const typename binary_t::container_type& value)
  886. {
  887. binary = create<binary_t>(value);
  888. }
  889. /// constructor for rvalue binary arrays
  890. json_value(typename binary_t::container_type&& value)
  891. {
  892. binary = create<binary_t>(std::move(value));
  893. }
  894. /// constructor for binary arrays (internal type)
  895. json_value(const binary_t& value)
  896. {
  897. binary = create<binary_t>(value);
  898. }
  899. /// constructor for rvalue binary arrays (internal type)
  900. json_value(binary_t&& value)
  901. {
  902. binary = create<binary_t>(std::move(value));
  903. }
  904. void destroy(value_t t) noexcept
  905. {
  906. // flatten the current json_value to a heap-allocated stack
  907. std::vector<basic_json> stack;
  908. // move the top-level items to stack
  909. if (t == value_t::array)
  910. {
  911. stack.reserve(array->size());
  912. std::move(array->begin(), array->end(), std::back_inserter(stack));
  913. }
  914. else if (t == value_t::object)
  915. {
  916. stack.reserve(object->size());
  917. for (auto&& it : *object)
  918. {
  919. stack.push_back(std::move(it.second));
  920. }
  921. }
  922. while (not stack.empty())
  923. {
  924. // move the last item to local variable to be processed
  925. basic_json current_item(std::move(stack.back()));
  926. stack.pop_back();
  927. // if current_item is array/object, move
  928. // its children to the stack to be processed later
  929. if (current_item.is_array())
  930. {
  931. std::move(current_item.m_value.array->begin(), current_item.m_value.array->end(),
  932. std::back_inserter(stack));
  933. current_item.m_value.array->clear();
  934. }
  935. else if (current_item.is_object())
  936. {
  937. for (auto&& it : *current_item.m_value.object)
  938. {
  939. stack.push_back(std::move(it.second));
  940. }
  941. current_item.m_value.object->clear();
  942. }
  943. // it's now safe that current_item get destructed
  944. // since it doesn't have any children
  945. }
  946. switch (t)
  947. {
  948. case value_t::object:
  949. {
  950. AllocatorType<object_t> alloc;
  951. std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
  952. std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
  953. break;
  954. }
  955. case value_t::array:
  956. {
  957. AllocatorType<array_t> alloc;
  958. std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
  959. std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
  960. break;
  961. }
  962. case value_t::string:
  963. {
  964. AllocatorType<string_t> alloc;
  965. std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
  966. std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
  967. break;
  968. }
  969. case value_t::binary:
  970. {
  971. AllocatorType<binary_t> alloc;
  972. std::allocator_traits<decltype(alloc)>::destroy(alloc, binary);
  973. std::allocator_traits<decltype(alloc)>::deallocate(alloc, binary, 1);
  974. break;
  975. }
  976. default:
  977. {
  978. break;
  979. }
  980. }
  981. }
  982. };
  983. /*!
  984. @brief checks the class invariants
  985. This function asserts the class invariants. It needs to be called at the
  986. end of every constructor to make sure that created objects respect the
  987. invariant. Furthermore, it has to be called each time the type of a JSON
  988. value is changed, because the invariant expresses a relationship between
  989. @a m_type and @a m_value.
  990. */
  991. void assert_invariant() const noexcept
  992. {
  993. assert(m_type != value_t::object or m_value.object != nullptr);
  994. assert(m_type != value_t::array or m_value.array != nullptr);
  995. assert(m_type != value_t::string or m_value.string != nullptr);
  996. assert(m_type != value_t::binary or m_value.binary != nullptr);
  997. }
  998. public:
  999. //////////////////////////
  1000. // JSON parser callback //
  1001. //////////////////////////
  1002. /*!
  1003. @brief parser event types
  1004. The parser callback distinguishes the following events:
  1005. - `object_start`: the parser read `{` and started to process a JSON object
  1006. - `key`: the parser read a key of a value in an object
  1007. - `object_end`: the parser read `}` and finished processing a JSON object
  1008. - `array_start`: the parser read `[` and started to process a JSON array
  1009. - `array_end`: the parser read `]` and finished processing a JSON array
  1010. - `value`: the parser finished reading a JSON value
  1011. @image html callback_events.png "Example when certain parse events are triggered"
  1012. @sa @ref parser_callback_t for more information and examples
  1013. */
  1014. using parse_event_t = detail::parse_event_t;
  1015. /*!
  1016. @brief per-element parser callback type
  1017. With a parser callback function, the result of parsing a JSON text can be
  1018. influenced. When passed to @ref parse, it is called on certain events
  1019. (passed as @ref parse_event_t via parameter @a event) with a set recursion
  1020. depth @a depth and context JSON value @a parsed. The return value of the
  1021. callback function is a boolean indicating whether the element that emitted
  1022. the callback shall be kept or not.
  1023. We distinguish six scenarios (determined by the event type) in which the
  1024. callback function can be called. The following table describes the values
  1025. of the parameters @a depth, @a event, and @a parsed.
  1026. parameter @a event | description | parameter @a depth | parameter @a parsed
  1027. ------------------ | ----------- | ------------------ | -------------------
  1028. parse_event_t::object_start | the parser read `{` and started to process a JSON object | depth of the parent of the JSON object | a JSON value with type discarded
  1029. parse_event_t::key | the parser read a key of a value in an object | depth of the currently parsed JSON object | a JSON string containing the key
  1030. parse_event_t::object_end | the parser read `}` and finished processing a JSON object | depth of the parent of the JSON object | the parsed JSON object
  1031. parse_event_t::array_start | the parser read `[` and started to process a JSON array | depth of the parent of the JSON array | a JSON value with type discarded
  1032. parse_event_t::array_end | the parser read `]` and finished processing a JSON array | depth of the parent of the JSON array | the parsed JSON array
  1033. parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
  1034. @image html callback_events.png "Example when certain parse events are triggered"
  1035. Discarding a value (i.e., returning `false`) has different effects
  1036. depending on the context in which function was called:
  1037. - Discarded values in structured types are skipped. That is, the parser
  1038. will behave as if the discarded value was never read.
  1039. - In case a value outside a structured type is skipped, it is replaced
  1040. with `null`. This case happens if the top-level element is skipped.
  1041. @param[in] depth the depth of the recursion during parsing
  1042. @param[in] event an event of type parse_event_t indicating the context in
  1043. the callback function has been called
  1044. @param[in,out] parsed the current intermediate parse result; note that
  1045. writing to this value has no effect for parse_event_t::key events
  1046. @return Whether the JSON value which called the function during parsing
  1047. should be kept (`true`) or not (`false`). In the latter case, it is either
  1048. skipped completely or replaced by an empty discarded object.
  1049. @sa @ref parse for examples
  1050. @since version 1.0.0
  1051. */
  1052. using parser_callback_t = detail::parser_callback_t<basic_json>;
  1053. //////////////////
  1054. // constructors //
  1055. //////////////////
  1056. /// @name constructors and destructors
  1057. /// Constructors of class @ref basic_json, copy/move constructor, copy
  1058. /// assignment, static functions creating objects, and the destructor.
  1059. /// @{
  1060. /*!
  1061. @brief create an empty value with a given type
  1062. Create an empty JSON value with a given type. The value will be default
  1063. initialized with an empty value which depends on the type:
  1064. Value type | initial value
  1065. ----------- | -------------
  1066. null | `null`
  1067. boolean | `false`
  1068. string | `""`
  1069. number | `0`
  1070. object | `{}`
  1071. array | `[]`
  1072. binary | empty array
  1073. @param[in] v the type of the value to create
  1074. @complexity Constant.
  1075. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  1076. changes to any JSON value.
  1077. @liveexample{The following code shows the constructor for different @ref
  1078. value_t values,basic_json__value_t}
  1079. @sa @ref clear() -- restores the postcondition of this constructor
  1080. @since version 1.0.0
  1081. */
  1082. basic_json(const value_t v)
  1083. : m_type(v), m_value(v)
  1084. {
  1085. assert_invariant();
  1086. }
  1087. /*!
  1088. @brief create a null object
  1089. Create a `null` JSON value. It either takes a null pointer as parameter
  1090. (explicitly creating `null`) or no parameter (implicitly creating `null`).
  1091. The passed null pointer itself is not read -- it is only used to choose
  1092. the right constructor.
  1093. @complexity Constant.
  1094. @exceptionsafety No-throw guarantee: this constructor never throws
  1095. exceptions.
  1096. @liveexample{The following code shows the constructor with and without a
  1097. null pointer parameter.,basic_json__nullptr_t}
  1098. @since version 1.0.0
  1099. */
  1100. basic_json(std::nullptr_t = nullptr) noexcept
  1101. : basic_json(value_t::null)
  1102. {
  1103. assert_invariant();
  1104. }
  1105. /*!
  1106. @brief create a JSON value
  1107. This is a "catch all" constructor for all compatible JSON types; that is,
  1108. types for which a `to_json()` method exists. The constructor forwards the
  1109. parameter @a val to that method (to `json_serializer<U>::to_json` method
  1110. with `U = uncvref_t<CompatibleType>`, to be exact).
  1111. Template type @a CompatibleType includes, but is not limited to, the
  1112. following types:
  1113. - **arrays**: @ref array_t and all kinds of compatible containers such as
  1114. `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
  1115. `std::array`, `std::valarray`, `std::set`, `std::unordered_set`,
  1116. `std::multiset`, and `std::unordered_multiset` with a `value_type` from
  1117. which a @ref basic_json value can be constructed.
  1118. - **objects**: @ref object_t and all kinds of compatible associative
  1119. containers such as `std::map`, `std::unordered_map`, `std::multimap`,
  1120. and `std::unordered_multimap` with a `key_type` compatible to
  1121. @ref string_t and a `value_type` from which a @ref basic_json value can
  1122. be constructed.
  1123. - **strings**: @ref string_t, string literals, and all compatible string
  1124. containers can be used.
  1125. - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
  1126. @ref number_float_t, and all convertible number types such as `int`,
  1127. `size_t`, `int64_t`, `float` or `double` can be used.
  1128. - **boolean**: @ref boolean_t / `bool` can be used.
  1129. - **binary**: @ref binary_t / `std::vector<uint8_t>` may be used,
  1130. unfortunately because string literals cannot be distinguished from binary
  1131. character arrays by the C++ type system, all types compatible with `const
  1132. char*` will be directed to the string constructor instead. This is both
  1133. for backwards compatibility, and due to the fact that a binary type is not
  1134. a standard JSON type.
  1135. See the examples below.
  1136. @tparam CompatibleType a type such that:
  1137. - @a CompatibleType is not derived from `std::istream`,
  1138. - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
  1139. constructors),
  1140. - @a CompatibleType is not a different @ref basic_json type (i.e. with different template arguments)
  1141. - @a CompatibleType is not a @ref basic_json nested type (e.g.,
  1142. @ref json_pointer, @ref iterator, etc ...)
  1143. - @ref @ref json_serializer<U> has a
  1144. `to_json(basic_json_t&, CompatibleType&&)` method
  1145. @tparam U = `uncvref_t<CompatibleType>`
  1146. @param[in] val the value to be forwarded to the respective constructor
  1147. @complexity Usually linear in the size of the passed @a val, also
  1148. depending on the implementation of the called `to_json()`
  1149. method.
  1150. @exceptionsafety Depends on the called constructor. For types directly
  1151. supported by the library (i.e., all types for which no `to_json()` function
  1152. was provided), strong guarantee holds: if an exception is thrown, there are
  1153. no changes to any JSON value.
  1154. @liveexample{The following code shows the constructor with several
  1155. compatible types.,basic_json__CompatibleType}
  1156. @since version 2.1.0
  1157. */
  1158. template <typename CompatibleType,
  1159. typename U = detail::uncvref_t<CompatibleType>,
  1160. detail::enable_if_t<
  1161. not detail::is_basic_json<U>::value and detail::is_compatible_type<basic_json_t, U>::value, int> = 0>
  1162. basic_json(CompatibleType && val) noexcept(noexcept(
  1163. JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
  1164. std::forward<CompatibleType>(val))))
  1165. {
  1166. JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
  1167. assert_invariant();
  1168. }
  1169. /*!
  1170. @brief create a JSON value from an existing one
  1171. This is a constructor for existing @ref basic_json types.
  1172. It does not hijack copy/move constructors, since the parameter has different
  1173. template arguments than the current ones.
  1174. The constructor tries to convert the internal @ref m_value of the parameter.
  1175. @tparam BasicJsonType a type such that:
  1176. - @a BasicJsonType is a @ref basic_json type.
  1177. - @a BasicJsonType has different template arguments than @ref basic_json_t.
  1178. @param[in] val the @ref basic_json value to be converted.
  1179. @complexity Usually linear in the size of the passed @a val, also
  1180. depending on the implementation of the called `to_json()`
  1181. method.
  1182. @exceptionsafety Depends on the called constructor. For types directly
  1183. supported by the library (i.e., all types for which no `to_json()` function
  1184. was provided), strong guarantee holds: if an exception is thrown, there are
  1185. no changes to any JSON value.
  1186. @since version 3.2.0
  1187. */
  1188. template <typename BasicJsonType,
  1189. detail::enable_if_t<
  1190. detail::is_basic_json<BasicJsonType>::value and not std::is_same<basic_json, BasicJsonType>::value, int> = 0>
  1191. basic_json(const BasicJsonType& val)
  1192. {
  1193. using other_boolean_t = typename BasicJsonType::boolean_t;
  1194. using other_number_float_t = typename BasicJsonType::number_float_t;
  1195. using other_number_integer_t = typename BasicJsonType::number_integer_t;
  1196. using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  1197. using other_string_t = typename BasicJsonType::string_t;
  1198. using other_object_t = typename BasicJsonType::object_t;
  1199. using other_array_t = typename BasicJsonType::array_t;
  1200. using other_binary_t = typename BasicJsonType::binary_t;
  1201. switch (val.type())
  1202. {
  1203. case value_t::boolean:
  1204. JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>());
  1205. break;
  1206. case value_t::number_float:
  1207. JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>());
  1208. break;
  1209. case value_t::number_integer:
  1210. JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>());
  1211. break;
  1212. case value_t::number_unsigned:
  1213. JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>());
  1214. break;
  1215. case value_t::string:
  1216. JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>());
  1217. break;
  1218. case value_t::object:
  1219. JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>());
  1220. break;
  1221. case value_t::array:
  1222. JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>());
  1223. break;
  1224. case value_t::binary:
  1225. JSONSerializer<other_binary_t>::to_json(*this, val.template get_ref<const other_binary_t&>());
  1226. break;
  1227. case value_t::null:
  1228. *this = nullptr;
  1229. break;
  1230. case value_t::discarded:
  1231. m_type = value_t::discarded;
  1232. break;
  1233. default: // LCOV_EXCL_LINE
  1234. assert(false); // LCOV_EXCL_LINE
  1235. }
  1236. assert_invariant();
  1237. }
  1238. /*!
  1239. @brief create a container (array or object) from an initializer list
  1240. Creates a JSON value of type array or object from the passed initializer
  1241. list @a init. In case @a type_deduction is `true` (default), the type of
  1242. the JSON value to be created is deducted from the initializer list @a init
  1243. according to the following rules:
  1244. 1. If the list is empty, an empty JSON object value `{}` is created.
  1245. 2. If the list consists of pairs whose first element is a string, a JSON
  1246. object value is created where the first elements of the pairs are
  1247. treated as keys and the second elements are as values.
  1248. 3. In all other cases, an array is created.
  1249. The rules aim to create the best fit between a C++ initializer list and
  1250. JSON values. The rationale is as follows:
  1251. 1. The empty initializer list is written as `{}` which is exactly an empty
  1252. JSON object.
  1253. 2. C++ has no way of describing mapped types other than to list a list of
  1254. pairs. As JSON requires that keys must be of type string, rule 2 is the
  1255. weakest constraint one can pose on initializer lists to interpret them
  1256. as an object.
  1257. 3. In all other cases, the initializer list could not be interpreted as
  1258. JSON object type, so interpreting it as JSON array type is safe.
  1259. With the rules described above, the following JSON values cannot be
  1260. expressed by an initializer list:
  1261. - the empty array (`[]`): use @ref array(initializer_list_t)
  1262. with an empty initializer list in this case
  1263. - arrays whose elements satisfy rule 2: use @ref
  1264. array(initializer_list_t) with the same initializer list
  1265. in this case
  1266. @note When used without parentheses around an empty initializer list, @ref
  1267. basic_json() is called instead of this function, yielding the JSON null
  1268. value.
  1269. @param[in] init initializer list with JSON values
  1270. @param[in] type_deduction internal parameter; when set to `true`, the type
  1271. of the JSON value is deducted from the initializer list @a init; when set
  1272. to `false`, the type provided via @a manual_type is forced. This mode is
  1273. used by the functions @ref array(initializer_list_t) and
  1274. @ref object(initializer_list_t).
  1275. @param[in] manual_type internal parameter; when @a type_deduction is set
  1276. to `false`, the created JSON value will use the provided type (only @ref
  1277. value_t::array and @ref value_t::object are valid); when @a type_deduction
  1278. is set to `true`, this parameter has no effect
  1279. @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
  1280. `value_t::object`, but @a init contains an element which is not a pair
  1281. whose first element is a string. In this case, the constructor could not
  1282. create an object. If @a type_deduction would have be `true`, an array
  1283. would have been created. See @ref object(initializer_list_t)
  1284. for an example.
  1285. @complexity Linear in the size of the initializer list @a init.
  1286. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  1287. changes to any JSON value.
  1288. @liveexample{The example below shows how JSON values are created from
  1289. initializer lists.,basic_json__list_init_t}
  1290. @sa @ref array(initializer_list_t) -- create a JSON array
  1291. value from an initializer list
  1292. @sa @ref object(initializer_list_t) -- create a JSON object
  1293. value from an initializer list
  1294. @since version 1.0.0
  1295. */
  1296. basic_json(initializer_list_t init,
  1297. bool type_deduction = true,
  1298. value_t manual_type = value_t::array)
  1299. {
  1300. // check if each element is an array with two elements whose first
  1301. // element is a string
  1302. bool is_an_object = std::all_of(init.begin(), init.end(),
  1303. [](const detail::json_ref<basic_json>& element_ref)
  1304. {
  1305. return element_ref->is_array() and element_ref->size() == 2 and (*element_ref)[0].is_string();
  1306. });
  1307. // adjust type if type deduction is not wanted
  1308. if (not type_deduction)
  1309. {
  1310. // if array is wanted, do not create an object though possible
  1311. if (manual_type == value_t::array)
  1312. {
  1313. is_an_object = false;
  1314. }
  1315. // if object is wanted but impossible, throw an exception
  1316. if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object and not is_an_object))
  1317. {
  1318. JSON_THROW(type_error::create(301, "cannot create object from initializer list"));
  1319. }
  1320. }
  1321. if (is_an_object)
  1322. {
  1323. // the initializer list is a list of pairs -> create object
  1324. m_type = value_t::object;
  1325. m_value = value_t::object;
  1326. std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref)
  1327. {
  1328. auto element = element_ref.moved_or_copied();
  1329. m_value.object->emplace(
  1330. std::move(*((*element.m_value.array)[0].m_value.string)),
  1331. std::move((*element.m_value.array)[1]));
  1332. });
  1333. }
  1334. else
  1335. {
  1336. // the initializer list describes an array -> create array
  1337. m_type = value_t::array;
  1338. m_value.array = create<array_t>(init.begin(), init.end());
  1339. }
  1340. assert_invariant();
  1341. }
  1342. /*!
  1343. @brief explicitly create a binary array (without subtype)
  1344. Creates a JSON binary array value from a given binary container. Binary
  1345. values are part of various binary formats, such as CBOR, MessagePack, and
  1346. BSON. This constructor is used to create a value for serialization to those
  1347. formats.
  1348. @note Note, this function exists because of the difficulty in correctly
  1349. specifying the correct template overload in the standard value ctor, as both
  1350. JSON arrays and JSON binary arrays are backed with some form of a
  1351. `std::vector`. Because JSON binary arrays are a non-standard extension it
  1352. was decided that it would be best to prevent automatic initialization of a
  1353. binary array type, for backwards compatibility and so it does not happen on
  1354. accident.
  1355. @param[in] init container containing bytes to use as binary type
  1356. @return JSON binary array value
  1357. @complexity Linear in the size of @a init.
  1358. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  1359. changes to any JSON value.
  1360. @since version 3.8.0
  1361. */
  1362. JSON_HEDLEY_WARN_UNUSED_RESULT
  1363. static basic_json binary(const typename binary_t::container_type& init)
  1364. {
  1365. auto res = basic_json();
  1366. res.m_type = value_t::binary;
  1367. res.m_value = init;
  1368. return res;
  1369. }
  1370. /*!
  1371. @brief explicitly create a binary array (with subtype)
  1372. Creates a JSON binary array value from a given binary container. Binary
  1373. values are part of various binary formats, such as CBOR, MessagePack, and
  1374. BSON. This constructor is used to create a value for serialization to those
  1375. formats.
  1376. @note Note, this function exists because of the difficulty in correctly
  1377. specifying the correct template overload in the standard value ctor, as both
  1378. JSON arrays and JSON binary arrays are backed with some form of a
  1379. `std::vector`. Because JSON binary arrays are a non-standard extension it
  1380. was decided that it would be best to prevent automatic initialization of a
  1381. binary array type, for backwards compatibility and so it does not happen on
  1382. accident.
  1383. @param[in] init container containing bytes to use as binary type
  1384. @param[in] subtype subtype to use in MessagePack and BSON
  1385. @return JSON binary array value
  1386. @complexity Linear in the size of @a init.
  1387. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  1388. changes to any JSON value.
  1389. @since version 3.8.0
  1390. */
  1391. JSON_HEDLEY_WARN_UNUSED_RESULT
  1392. static basic_json binary(const typename binary_t::container_type& init, std::uint8_t subtype)
  1393. {
  1394. auto res = basic_json();
  1395. res.m_type = value_t::binary;
  1396. res.m_value = binary_t(init, subtype);
  1397. return res;
  1398. }
  1399. /// @copydoc binary(const typename binary_t::container_type&)
  1400. JSON_HEDLEY_WARN_UNUSED_RESULT
  1401. static basic_json binary(typename binary_t::container_type&& init)
  1402. {
  1403. auto res = basic_json();
  1404. res.m_type = value_t::binary;
  1405. res.m_value = std::move(init);
  1406. return res;
  1407. }
  1408. /// @copydoc binary(const typename binary_t::container_type&, std::uint8_t)
  1409. JSON_HEDLEY_WARN_UNUSED_RESULT
  1410. static basic_json binary(typename binary_t::container_type&& init, std::uint8_t subtype)
  1411. {
  1412. auto res = basic_json();
  1413. res.m_type = value_t::binary;
  1414. res.m_value = binary_t(std::move(init), subtype);
  1415. return res;
  1416. }
  1417. /*!
  1418. @brief explicitly create an array from an initializer list
  1419. Creates a JSON array value from a given initializer list. That is, given a
  1420. list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
  1421. initializer list is empty, the empty array `[]` is created.
  1422. @note This function is only needed to express two edge cases that cannot
  1423. be realized with the initializer list constructor (@ref
  1424. basic_json(initializer_list_t, bool, value_t)). These cases
  1425. are:
  1426. 1. creating an array whose elements are all pairs whose first element is a
  1427. string -- in this case, the initializer list constructor would create an
  1428. object, taking the first elements as keys
  1429. 2. creating an empty array -- passing the empty initializer list to the
  1430. initializer list constructor yields an empty object
  1431. @param[in] init initializer list with JSON values to create an array from
  1432. (optional)
  1433. @return JSON array value
  1434. @complexity Linear in the size of @a init.
  1435. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  1436. changes to any JSON value.
  1437. @liveexample{The following code shows an example for the `array`
  1438. function.,array}
  1439. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  1440. create a JSON value from an initializer list
  1441. @sa @ref object(initializer_list_t) -- create a JSON object
  1442. value from an initializer list
  1443. @since version 1.0.0
  1444. */
  1445. JSON_HEDLEY_WARN_UNUSED_RESULT
  1446. static basic_json array(initializer_list_t init = {})
  1447. {
  1448. return basic_json(init, false, value_t::array);
  1449. }
  1450. /*!
  1451. @brief explicitly create an object from an initializer list
  1452. Creates a JSON object value from a given initializer list. The initializer
  1453. lists elements must be pairs, and their first elements must be strings. If
  1454. the initializer list is empty, the empty object `{}` is created.
  1455. @note This function is only added for symmetry reasons. In contrast to the
  1456. related function @ref array(initializer_list_t), there are
  1457. no cases which can only be expressed by this function. That is, any
  1458. initializer list @a init can also be passed to the initializer list
  1459. constructor @ref basic_json(initializer_list_t, bool, value_t).
  1460. @param[in] init initializer list to create an object from (optional)
  1461. @return JSON object value
  1462. @throw type_error.301 if @a init is not a list of pairs whose first
  1463. elements are strings. In this case, no object can be created. When such a
  1464. value is passed to @ref basic_json(initializer_list_t, bool, value_t),
  1465. an array would have been created from the passed initializer list @a init.
  1466. See example below.
  1467. @complexity Linear in the size of @a init.
  1468. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  1469. changes to any JSON value.
  1470. @liveexample{The following code shows an example for the `object`
  1471. function.,object}
  1472. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  1473. create a JSON value from an initializer list
  1474. @sa @ref array(initializer_list_t) -- create a JSON array
  1475. value from an initializer list
  1476. @since version 1.0.0
  1477. */
  1478. JSON_HEDLEY_WARN_UNUSED_RESULT
  1479. static basic_json object(initializer_list_t init = {})
  1480. {
  1481. return basic_json(init, false, value_t::object);
  1482. }
  1483. /*!
  1484. @brief construct an array with count copies of given value
  1485. Constructs a JSON array value by creating @a cnt copies of a passed value.
  1486. In case @a cnt is `0`, an empty array is created.
  1487. @param[in] cnt the number of JSON copies of @a val to create
  1488. @param[in] val the JSON value to copy
  1489. @post `std::distance(begin(),end()) == cnt` holds.
  1490. @complexity Linear in @a cnt.
  1491. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  1492. changes to any JSON value.
  1493. @liveexample{The following code shows examples for the @ref
  1494. basic_json(size_type\, const basic_json&)
  1495. constructor.,basic_json__size_type_basic_json}
  1496. @since version 1.0.0
  1497. */
  1498. basic_json(size_type cnt, const basic_json& val)
  1499. : m_type(value_t::array)
  1500. {
  1501. m_value.array = create<array_t>(cnt, val);
  1502. assert_invariant();
  1503. }
  1504. /*!
  1505. @brief construct a JSON container given an iterator range
  1506. Constructs the JSON value with the contents of the range `[first, last)`.
  1507. The semantics depends on the different types a JSON value can have:
  1508. - In case of a null type, invalid_iterator.206 is thrown.
  1509. - In case of other primitive types (number, boolean, or string), @a first
  1510. must be `begin()` and @a last must be `end()`. In this case, the value is
  1511. copied. Otherwise, invalid_iterator.204 is thrown.
  1512. - In case of structured types (array, object), the constructor behaves as
  1513. similar versions for `std::vector` or `std::map`; that is, a JSON array
  1514. or object is constructed from the values in the range.
  1515. @tparam InputIT an input iterator type (@ref iterator or @ref
  1516. const_iterator)
  1517. @param[in] first begin of the range to copy from (included)
  1518. @param[in] last end of the range to copy from (excluded)
  1519. @pre Iterators @a first and @a last must be initialized. **This
  1520. precondition is enforced with an assertion (see warning).** If
  1521. assertions are switched off, a violation of this precondition yields
  1522. undefined behavior.
  1523. @pre Range `[first, last)` is valid. Usually, this precondition cannot be
  1524. checked efficiently. Only certain edge cases are detected; see the
  1525. description of the exceptions below. A violation of this precondition
  1526. yields undefined behavior.
  1527. @warning A precondition is enforced with a runtime assertion that will
  1528. result in calling `std::abort` if this precondition is not met.
  1529. Assertions can be disabled by defining `NDEBUG` at compile time.
  1530. See https://en.cppreference.com/w/cpp/error/assert for more
  1531. information.
  1532. @throw invalid_iterator.201 if iterators @a first and @a last are not
  1533. compatible (i.e., do not belong to the same JSON value). In this case,
  1534. the range `[first, last)` is undefined.
  1535. @throw invalid_iterator.204 if iterators @a first and @a last belong to a
  1536. primitive type (number, boolean, or string), but @a first does not point
  1537. to the first element any more. In this case, the range `[first, last)` is
  1538. undefined. See example code below.
  1539. @throw invalid_iterator.206 if iterators @a first and @a last belong to a
  1540. null value. In this case, the range `[first, last)` is undefined.
  1541. @complexity Linear in distance between @a first and @a last.
  1542. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  1543. changes to any JSON value.
  1544. @liveexample{The example below shows several ways to create JSON values by
  1545. specifying a subrange with iterators.,basic_json__InputIt_InputIt}
  1546. @since version 1.0.0
  1547. */
  1548. template<class InputIT, typename std::enable_if<
  1549. std::is_same<InputIT, typename basic_json_t::iterator>::value or
  1550. std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0>
  1551. basic_json(InputIT first, InputIT last)
  1552. {
  1553. assert(first.m_object != nullptr);
  1554. assert(last.m_object != nullptr);
  1555. // make sure iterator fits the current value
  1556. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  1557. {
  1558. JSON_THROW(invalid_iterator::create(201, "iterators are not compatible"));
  1559. }
  1560. // copy type from first iterator
  1561. m_type = first.m_object->m_type;
  1562. // check if iterator range is complete for primitive values
  1563. switch (m_type)
  1564. {
  1565. case value_t::boolean:
  1566. case value_t::number_float:
  1567. case value_t::number_integer:
  1568. case value_t::number_unsigned:
  1569. case value_t::string:
  1570. {
  1571. if (JSON_HEDLEY_UNLIKELY(not first.m_it.primitive_iterator.is_begin()
  1572. or not last.m_it.primitive_iterator.is_end()))
  1573. {
  1574. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  1575. }
  1576. break;
  1577. }
  1578. default:
  1579. break;
  1580. }
  1581. switch (m_type)
  1582. {
  1583. case value_t::number_integer:
  1584. {
  1585. m_value.number_integer = first.m_object->m_value.number_integer;
  1586. break;
  1587. }
  1588. case value_t::number_unsigned:
  1589. {
  1590. m_value.number_unsigned = first.m_object->m_value.number_unsigned;
  1591. break;
  1592. }
  1593. case value_t::number_float:
  1594. {
  1595. m_value.number_float = first.m_object->m_value.number_float;
  1596. break;
  1597. }
  1598. case value_t::boolean:
  1599. {
  1600. m_value.boolean = first.m_object->m_value.boolean;
  1601. break;
  1602. }
  1603. case value_t::string:
  1604. {
  1605. m_value = *first.m_object->m_value.string;
  1606. break;
  1607. }
  1608. case value_t::object:
  1609. {
  1610. m_value.object = create<object_t>(first.m_it.object_iterator,
  1611. last.m_it.object_iterator);
  1612. break;
  1613. }
  1614. case value_t::array:
  1615. {
  1616. m_value.array = create<array_t>(first.m_it.array_iterator,
  1617. last.m_it.array_iterator);
  1618. break;
  1619. }
  1620. case value_t::binary:
  1621. {
  1622. m_value = *first.m_object->m_value.binary;
  1623. break;
  1624. }
  1625. default:
  1626. JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " +
  1627. std::string(first.m_object->type_name())));
  1628. }
  1629. assert_invariant();
  1630. }
  1631. ///////////////////////////////////////
  1632. // other constructors and destructor //
  1633. ///////////////////////////////////////
  1634. template <typename JsonRef,
  1635. detail::enable_if_t<detail::conjunction<detail::is_json_ref<JsonRef>,
  1636. std::is_same<typename JsonRef::value_type, basic_json>>::value, int> = 0 >
  1637. basic_json(const JsonRef& ref) : basic_json(ref.moved_or_copied()) {}
  1638. /*!
  1639. @brief copy constructor
  1640. Creates a copy of a given JSON value.
  1641. @param[in] other the JSON value to copy
  1642. @post `*this == other`
  1643. @complexity Linear in the size of @a other.
  1644. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  1645. changes to any JSON value.
  1646. @requirement This function helps `basic_json` satisfying the
  1647. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  1648. requirements:
  1649. - The complexity is linear.
  1650. - As postcondition, it holds: `other == basic_json(other)`.
  1651. @liveexample{The following code shows an example for the copy
  1652. constructor.,basic_json__basic_json}
  1653. @since version 1.0.0
  1654. */
  1655. basic_json(const basic_json& other)
  1656. : m_type(other.m_type)
  1657. {
  1658. // check of passed value is valid
  1659. other.assert_invariant();
  1660. switch (m_type)
  1661. {
  1662. case value_t::object:
  1663. {
  1664. m_value = *other.m_value.object;
  1665. break;
  1666. }
  1667. case value_t::array:
  1668. {
  1669. m_value = *other.m_value.array;
  1670. break;
  1671. }
  1672. case value_t::string:
  1673. {
  1674. m_value = *other.m_value.string;
  1675. break;
  1676. }
  1677. case value_t::boolean:
  1678. {
  1679. m_value = other.m_value.boolean;
  1680. break;
  1681. }
  1682. case value_t::number_integer:
  1683. {
  1684. m_value = other.m_value.number_integer;
  1685. break;
  1686. }
  1687. case value_t::number_unsigned:
  1688. {
  1689. m_value = other.m_value.number_unsigned;
  1690. break;
  1691. }
  1692. case value_t::number_float:
  1693. {
  1694. m_value = other.m_value.number_float;
  1695. break;
  1696. }
  1697. case value_t::binary:
  1698. {
  1699. m_value = *other.m_value.binary;
  1700. break;
  1701. }
  1702. default:
  1703. break;
  1704. }
  1705. assert_invariant();
  1706. }
  1707. /*!
  1708. @brief move constructor
  1709. Move constructor. Constructs a JSON value with the contents of the given
  1710. value @a other using move semantics. It "steals" the resources from @a
  1711. other and leaves it as JSON null value.
  1712. @param[in,out] other value to move to this object
  1713. @post `*this` has the same value as @a other before the call.
  1714. @post @a other is a JSON null value.
  1715. @complexity Constant.
  1716. @exceptionsafety No-throw guarantee: this constructor never throws
  1717. exceptions.
  1718. @requirement This function helps `basic_json` satisfying the
  1719. [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible)
  1720. requirements.
  1721. @liveexample{The code below shows the move constructor explicitly called
  1722. via std::move.,basic_json__moveconstructor}
  1723. @since version 1.0.0
  1724. */
  1725. basic_json(basic_json&& other) noexcept
  1726. : m_type(std::move(other.m_type)),
  1727. m_value(std::move(other.m_value))
  1728. {
  1729. // check that passed value is valid
  1730. other.assert_invariant();
  1731. // invalidate payload
  1732. other.m_type = value_t::null;
  1733. other.m_value = {};
  1734. assert_invariant();
  1735. }
  1736. /*!
  1737. @brief copy assignment
  1738. Copy assignment operator. Copies a JSON value via the "copy and swap"
  1739. strategy: It is expressed in terms of the copy constructor, destructor,
  1740. and the `swap()` member function.
  1741. @param[in] other value to copy from
  1742. @complexity Linear.
  1743. @requirement This function helps `basic_json` satisfying the
  1744. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  1745. requirements:
  1746. - The complexity is linear.
  1747. @liveexample{The code below shows and example for the copy assignment. It
  1748. creates a copy of value `a` which is then swapped with `b`. Finally\, the
  1749. copy of `a` (which is the null value after the swap) is
  1750. destroyed.,basic_json__copyassignment}
  1751. @since version 1.0.0
  1752. */
  1753. basic_json& operator=(basic_json other) noexcept (
  1754. std::is_nothrow_move_constructible<value_t>::value and
  1755. std::is_nothrow_move_assignable<value_t>::value and
  1756. std::is_nothrow_move_constructible<json_value>::value and
  1757. std::is_nothrow_move_assignable<json_value>::value
  1758. )
  1759. {
  1760. // check that passed value is valid
  1761. other.assert_invariant();
  1762. using std::swap;
  1763. swap(m_type, other.m_type);
  1764. swap(m_value, other.m_value);
  1765. assert_invariant();
  1766. return *this;
  1767. }
  1768. /*!
  1769. @brief destructor
  1770. Destroys the JSON value and frees all allocated memory.
  1771. @complexity Linear.
  1772. @requirement This function helps `basic_json` satisfying the
  1773. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  1774. requirements:
  1775. - The complexity is linear.
  1776. - All stored elements are destroyed and all memory is freed.
  1777. @since version 1.0.0
  1778. */
  1779. ~basic_json() noexcept
  1780. {
  1781. assert_invariant();
  1782. m_value.destroy(m_type);
  1783. }
  1784. /// @}
  1785. public:
  1786. ///////////////////////
  1787. // object inspection //
  1788. ///////////////////////
  1789. /// @name object inspection
  1790. /// Functions to inspect the type of a JSON value.
  1791. /// @{
  1792. /*!
  1793. @brief serialization
  1794. Serialization function for JSON values. The function tries to mimic
  1795. Python's `json.dumps()` function, and currently supports its @a indent
  1796. and @a ensure_ascii parameters.
  1797. @param[in] indent If indent is nonnegative, then array elements and object
  1798. members will be pretty-printed with that indent level. An indent level of
  1799. `0` will only insert newlines. `-1` (the default) selects the most compact
  1800. representation.
  1801. @param[in] indent_char The character to use for indentation if @a indent is
  1802. greater than `0`. The default is ` ` (space).
  1803. @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
  1804. in the output are escaped with `\uXXXX` sequences, and the result consists
  1805. of ASCII characters only.
  1806. @param[in] error_handler how to react on decoding errors; there are three
  1807. possible values: `strict` (throws and exception in case a decoding error
  1808. occurs; default), `replace` (replace invalid UTF-8 sequences with U+FFFD),
  1809. and `ignore` (ignore invalid UTF-8 sequences during serialization).
  1810. @return string containing the serialization of the JSON value
  1811. @throw type_error.316 if a string stored inside the JSON value is not
  1812. UTF-8 encoded and @a error_handler is set to strict
  1813. @note Binary values are serialized as object containing two keys:
  1814. - "bytes": an array of bytes as integers
  1815. - "subtype": the subtype as integer or "null" if the binary has no subtype
  1816. @complexity Linear.
  1817. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  1818. changes in the JSON value.
  1819. @liveexample{The following example shows the effect of different @a indent\,
  1820. @a indent_char\, and @a ensure_ascii parameters to the result of the
  1821. serialization.,dump}
  1822. @see https://docs.python.org/2/library/json.html#json.dump
  1823. @since version 1.0.0; indentation character @a indent_char, option
  1824. @a ensure_ascii and exceptions added in version 3.0.0; error
  1825. handlers added in version 3.4.0; serialization of binary values added
  1826. in version 3.8.0.
  1827. */
  1828. string_t dump(const int indent = -1,
  1829. const char indent_char = ' ',
  1830. const bool ensure_ascii = false,
  1831. const error_handler_t error_handler = error_handler_t::strict) const
  1832. {
  1833. string_t result;
  1834. serializer s(detail::output_adapter<char, string_t>(result), indent_char, error_handler);
  1835. if (indent >= 0)
  1836. {
  1837. s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
  1838. }
  1839. else
  1840. {
  1841. s.dump(*this, false, ensure_ascii, 0);
  1842. }
  1843. return result;
  1844. }
  1845. /*!
  1846. @brief return the type of the JSON value (explicit)
  1847. Return the type of the JSON value as a value from the @ref value_t
  1848. enumeration.
  1849. @return the type of the JSON value
  1850. Value type | return value
  1851. ------------------------- | -------------------------
  1852. null | value_t::null
  1853. boolean | value_t::boolean
  1854. string | value_t::string
  1855. number (integer) | value_t::number_integer
  1856. number (unsigned integer) | value_t::number_unsigned
  1857. number (floating-point) | value_t::number_float
  1858. object | value_t::object
  1859. array | value_t::array
  1860. binary | value_t::binary
  1861. discarded | value_t::discarded
  1862. @complexity Constant.
  1863. @exceptionsafety No-throw guarantee: this member function never throws
  1864. exceptions.
  1865. @liveexample{The following code exemplifies `type()` for all JSON
  1866. types.,type}
  1867. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  1868. @sa @ref type_name() -- return the type as string
  1869. @since version 1.0.0
  1870. */
  1871. constexpr value_t type() const noexcept
  1872. {
  1873. return m_type;
  1874. }
  1875. /*!
  1876. @brief return whether type is primitive
  1877. This function returns true if and only if the JSON type is primitive
  1878. (string, number, boolean, or null).
  1879. @return `true` if type is primitive (string, number, boolean, or null),
  1880. `false` otherwise.
  1881. @complexity Constant.
  1882. @exceptionsafety No-throw guarantee: this member function never throws
  1883. exceptions.
  1884. @liveexample{The following code exemplifies `is_primitive()` for all JSON
  1885. types.,is_primitive}
  1886. @sa @ref is_structured() -- returns whether JSON value is structured
  1887. @sa @ref is_null() -- returns whether JSON value is `null`
  1888. @sa @ref is_string() -- returns whether JSON value is a string
  1889. @sa @ref is_boolean() -- returns whether JSON value is a boolean
  1890. @sa @ref is_number() -- returns whether JSON value is a number
  1891. @sa @ref is_binary() -- returns whether JSON value is a binary array
  1892. @since version 1.0.0
  1893. */
  1894. constexpr bool is_primitive() const noexcept
  1895. {
  1896. return is_null() or is_string() or is_boolean() or is_number() or is_binary();
  1897. }
  1898. /*!
  1899. @brief return whether type is structured
  1900. This function returns true if and only if the JSON type is structured
  1901. (array or object).
  1902. @return `true` if type is structured (array or object), `false` otherwise.
  1903. @complexity Constant.
  1904. @exceptionsafety No-throw guarantee: this member function never throws
  1905. exceptions.
  1906. @liveexample{The following code exemplifies `is_structured()` for all JSON
  1907. types.,is_structured}
  1908. @sa @ref is_primitive() -- returns whether value is primitive
  1909. @sa @ref is_array() -- returns whether value is an array
  1910. @sa @ref is_object() -- returns whether value is an object
  1911. @since version 1.0.0
  1912. */
  1913. constexpr bool is_structured() const noexcept
  1914. {
  1915. return is_array() or is_object();
  1916. }
  1917. /*!
  1918. @brief return whether value is null
  1919. This function returns true if and only if the JSON value is null.
  1920. @return `true` if type is null, `false` otherwise.
  1921. @complexity Constant.
  1922. @exceptionsafety No-throw guarantee: this member function never throws
  1923. exceptions.
  1924. @liveexample{The following code exemplifies `is_null()` for all JSON
  1925. types.,is_null}
  1926. @since version 1.0.0
  1927. */
  1928. constexpr bool is_null() const noexcept
  1929. {
  1930. return m_type == value_t::null;
  1931. }
  1932. /*!
  1933. @brief return whether value is a boolean
  1934. This function returns true if and only if the JSON value is a boolean.
  1935. @return `true` if type is boolean, `false` otherwise.
  1936. @complexity Constant.
  1937. @exceptionsafety No-throw guarantee: this member function never throws
  1938. exceptions.
  1939. @liveexample{The following code exemplifies `is_boolean()` for all JSON
  1940. types.,is_boolean}
  1941. @since version 1.0.0
  1942. */
  1943. constexpr bool is_boolean() const noexcept
  1944. {
  1945. return m_type == value_t::boolean;
  1946. }
  1947. /*!
  1948. @brief return whether value is a number
  1949. This function returns true if and only if the JSON value is a number. This
  1950. includes both integer (signed and unsigned) and floating-point values.
  1951. @return `true` if type is number (regardless whether integer, unsigned
  1952. integer or floating-type), `false` otherwise.
  1953. @complexity Constant.
  1954. @exceptionsafety No-throw guarantee: this member function never throws
  1955. exceptions.
  1956. @liveexample{The following code exemplifies `is_number()` for all JSON
  1957. types.,is_number}
  1958. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  1959. integer number
  1960. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  1961. number
  1962. @sa @ref is_number_float() -- check if value is a floating-point number
  1963. @since version 1.0.0
  1964. */
  1965. constexpr bool is_number() const noexcept
  1966. {
  1967. return is_number_integer() or is_number_float();
  1968. }
  1969. /*!
  1970. @brief return whether value is an integer number
  1971. This function returns true if and only if the JSON value is a signed or
  1972. unsigned integer number. This excludes floating-point values.
  1973. @return `true` if type is an integer or unsigned integer number, `false`
  1974. otherwise.
  1975. @complexity Constant.
  1976. @exceptionsafety No-throw guarantee: this member function never throws
  1977. exceptions.
  1978. @liveexample{The following code exemplifies `is_number_integer()` for all
  1979. JSON types.,is_number_integer}
  1980. @sa @ref is_number() -- check if value is a number
  1981. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  1982. number
  1983. @sa @ref is_number_float() -- check if value is a floating-point number
  1984. @since version 1.0.0
  1985. */
  1986. constexpr bool is_number_integer() const noexcept
  1987. {
  1988. return m_type == value_t::number_integer or m_type == value_t::number_unsigned;
  1989. }
  1990. /*!
  1991. @brief return whether value is an unsigned integer number
  1992. This function returns true if and only if the JSON value is an unsigned
  1993. integer number. This excludes floating-point and signed integer values.
  1994. @return `true` if type is an unsigned integer number, `false` otherwise.
  1995. @complexity Constant.
  1996. @exceptionsafety No-throw guarantee: this member function never throws
  1997. exceptions.
  1998. @liveexample{The following code exemplifies `is_number_unsigned()` for all
  1999. JSON types.,is_number_unsigned}
  2000. @sa @ref is_number() -- check if value is a number
  2001. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  2002. integer number
  2003. @sa @ref is_number_float() -- check if value is a floating-point number
  2004. @since version 2.0.0
  2005. */
  2006. constexpr bool is_number_unsigned() const noexcept
  2007. {
  2008. return m_type == value_t::number_unsigned;
  2009. }
  2010. /*!
  2011. @brief return whether value is a floating-point number
  2012. This function returns true if and only if the JSON value is a
  2013. floating-point number. This excludes signed and unsigned integer values.
  2014. @return `true` if type is a floating-point number, `false` otherwise.
  2015. @complexity Constant.
  2016. @exceptionsafety No-throw guarantee: this member function never throws
  2017. exceptions.
  2018. @liveexample{The following code exemplifies `is_number_float()` for all
  2019. JSON types.,is_number_float}
  2020. @sa @ref is_number() -- check if value is number
  2021. @sa @ref is_number_integer() -- check if value is an integer number
  2022. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  2023. number
  2024. @since version 1.0.0
  2025. */
  2026. constexpr bool is_number_float() const noexcept
  2027. {
  2028. return m_type == value_t::number_float;
  2029. }
  2030. /*!
  2031. @brief return whether value is an object
  2032. This function returns true if and only if the JSON value is an object.
  2033. @return `true` if type is object, `false` otherwise.
  2034. @complexity Constant.
  2035. @exceptionsafety No-throw guarantee: this member function never throws
  2036. exceptions.
  2037. @liveexample{The following code exemplifies `is_object()` for all JSON
  2038. types.,is_object}
  2039. @since version 1.0.0
  2040. */
  2041. constexpr bool is_object() const noexcept
  2042. {
  2043. return m_type == value_t::object;
  2044. }
  2045. /*!
  2046. @brief return whether value is an array
  2047. This function returns true if and only if the JSON value is an array.
  2048. @return `true` if type is array, `false` otherwise.
  2049. @complexity Constant.
  2050. @exceptionsafety No-throw guarantee: this member function never throws
  2051. exceptions.
  2052. @liveexample{The following code exemplifies `is_array()` for all JSON
  2053. types.,is_array}
  2054. @since version 1.0.0
  2055. */
  2056. constexpr bool is_array() const noexcept
  2057. {
  2058. return m_type == value_t::array;
  2059. }
  2060. /*!
  2061. @brief return whether value is a string
  2062. This function returns true if and only if the JSON value is a string.
  2063. @return `true` if type is string, `false` otherwise.
  2064. @complexity Constant.
  2065. @exceptionsafety No-throw guarantee: this member function never throws
  2066. exceptions.
  2067. @liveexample{The following code exemplifies `is_string()` for all JSON
  2068. types.,is_string}
  2069. @since version 1.0.0
  2070. */
  2071. constexpr bool is_string() const noexcept
  2072. {
  2073. return m_type == value_t::string;
  2074. }
  2075. /*!
  2076. @brief return whether value is a binary array
  2077. This function returns true if and only if the JSON value is a binary array.
  2078. @return `true` if type is binary array, `false` otherwise.
  2079. @complexity Constant.
  2080. @exceptionsafety No-throw guarantee: this member function never throws
  2081. exceptions.
  2082. @liveexample{The following code exemplifies `is_binary()` for all JSON
  2083. types.,is_binary}
  2084. @since version 3.8.0
  2085. */
  2086. constexpr bool is_binary() const noexcept
  2087. {
  2088. return m_type == value_t::binary;
  2089. }
  2090. /*!
  2091. @brief return whether value is discarded
  2092. This function returns true if and only if the JSON value was discarded
  2093. during parsing with a callback function (see @ref parser_callback_t).
  2094. @note This function will always be `false` for JSON values after parsing.
  2095. That is, discarded values can only occur during parsing, but will be
  2096. removed when inside a structured value or replaced by null in other cases.
  2097. @return `true` if type is discarded, `false` otherwise.
  2098. @complexity Constant.
  2099. @exceptionsafety No-throw guarantee: this member function never throws
  2100. exceptions.
  2101. @liveexample{The following code exemplifies `is_discarded()` for all JSON
  2102. types.,is_discarded}
  2103. @since version 1.0.0
  2104. */
  2105. constexpr bool is_discarded() const noexcept
  2106. {
  2107. return m_type == value_t::discarded;
  2108. }
  2109. /*!
  2110. @brief return the type of the JSON value (implicit)
  2111. Implicitly return the type of the JSON value as a value from the @ref
  2112. value_t enumeration.
  2113. @return the type of the JSON value
  2114. @complexity Constant.
  2115. @exceptionsafety No-throw guarantee: this member function never throws
  2116. exceptions.
  2117. @liveexample{The following code exemplifies the @ref value_t operator for
  2118. all JSON types.,operator__value_t}
  2119. @sa @ref type() -- return the type of the JSON value (explicit)
  2120. @sa @ref type_name() -- return the type as string
  2121. @since version 1.0.0
  2122. */
  2123. constexpr operator value_t() const noexcept
  2124. {
  2125. return m_type;
  2126. }
  2127. /// @}
  2128. private:
  2129. //////////////////
  2130. // value access //
  2131. //////////////////
  2132. /// get a boolean (explicit)
  2133. boolean_t get_impl(boolean_t* /*unused*/) const
  2134. {
  2135. if (JSON_HEDLEY_LIKELY(is_boolean()))
  2136. {
  2137. return m_value.boolean;
  2138. }
  2139. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name())));
  2140. }
  2141. /// get a pointer to the value (object)
  2142. object_t* get_impl_ptr(object_t* /*unused*/) noexcept
  2143. {
  2144. return is_object() ? m_value.object : nullptr;
  2145. }
  2146. /// get a pointer to the value (object)
  2147. constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
  2148. {
  2149. return is_object() ? m_value.object : nullptr;
  2150. }
  2151. /// get a pointer to the value (array)
  2152. array_t* get_impl_ptr(array_t* /*unused*/) noexcept
  2153. {
  2154. return is_array() ? m_value.array : nullptr;
  2155. }
  2156. /// get a pointer to the value (array)
  2157. constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
  2158. {
  2159. return is_array() ? m_value.array : nullptr;
  2160. }
  2161. /// get a pointer to the value (string)
  2162. string_t* get_impl_ptr(string_t* /*unused*/) noexcept
  2163. {
  2164. return is_string() ? m_value.string : nullptr;
  2165. }
  2166. /// get a pointer to the value (string)
  2167. constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
  2168. {
  2169. return is_string() ? m_value.string : nullptr;
  2170. }
  2171. /// get a pointer to the value (boolean)
  2172. boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
  2173. {
  2174. return is_boolean() ? &m_value.boolean : nullptr;
  2175. }
  2176. /// get a pointer to the value (boolean)
  2177. constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
  2178. {
  2179. return is_boolean() ? &m_value.boolean : nullptr;
  2180. }
  2181. /// get a pointer to the value (integer number)
  2182. number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
  2183. {
  2184. return is_number_integer() ? &m_value.number_integer : nullptr;
  2185. }
  2186. /// get a pointer to the value (integer number)
  2187. constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
  2188. {
  2189. return is_number_integer() ? &m_value.number_integer : nullptr;
  2190. }
  2191. /// get a pointer to the value (unsigned number)
  2192. number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
  2193. {
  2194. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  2195. }
  2196. /// get a pointer to the value (unsigned number)
  2197. constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
  2198. {
  2199. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  2200. }
  2201. /// get a pointer to the value (floating-point number)
  2202. number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
  2203. {
  2204. return is_number_float() ? &m_value.number_float : nullptr;
  2205. }
  2206. /// get a pointer to the value (floating-point number)
  2207. constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
  2208. {
  2209. return is_number_float() ? &m_value.number_float : nullptr;
  2210. }
  2211. /// get a pointer to the value (binary)
  2212. binary_t* get_impl_ptr(binary_t* /*unused*/) noexcept
  2213. {
  2214. return is_binary() ? m_value.binary : nullptr;
  2215. }
  2216. /// get a pointer to the value (binary)
  2217. constexpr const binary_t* get_impl_ptr(const binary_t* /*unused*/) const noexcept
  2218. {
  2219. return is_binary() ? m_value.binary : nullptr;
  2220. }
  2221. /*!
  2222. @brief helper function to implement get_ref()
  2223. This function helps to implement get_ref() without code duplication for
  2224. const and non-const overloads
  2225. @tparam ThisType will be deduced as `basic_json` or `const basic_json`
  2226. @throw type_error.303 if ReferenceType does not match underlying value
  2227. type of the current JSON
  2228. */
  2229. template<typename ReferenceType, typename ThisType>
  2230. static ReferenceType get_ref_impl(ThisType& obj)
  2231. {
  2232. // delegate the call to get_ptr<>()
  2233. auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
  2234. if (JSON_HEDLEY_LIKELY(ptr != nullptr))
  2235. {
  2236. return *ptr;
  2237. }
  2238. JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name())));
  2239. }
  2240. public:
  2241. /// @name value access
  2242. /// Direct access to the stored value of a JSON value.
  2243. /// @{
  2244. /*!
  2245. @brief get special-case overload
  2246. This overloads avoids a lot of template boilerplate, it can be seen as the
  2247. identity method
  2248. @tparam BasicJsonType == @ref basic_json
  2249. @return a copy of *this
  2250. @complexity Constant.
  2251. @since version 2.1.0
  2252. */
  2253. template<typename BasicJsonType, detail::enable_if_t<
  2254. std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value,
  2255. int> = 0>
  2256. basic_json get() const
  2257. {
  2258. return *this;
  2259. }
  2260. /*!
  2261. @brief get special-case overload
  2262. This overloads converts the current @ref basic_json in a different
  2263. @ref basic_json type
  2264. @tparam BasicJsonType == @ref basic_json
  2265. @return a copy of *this, converted into @tparam BasicJsonType
  2266. @complexity Depending on the implementation of the called `from_json()`
  2267. method.
  2268. @since version 3.2.0
  2269. */
  2270. template<typename BasicJsonType, detail::enable_if_t<
  2271. not std::is_same<BasicJsonType, basic_json>::value and
  2272. detail::is_basic_json<BasicJsonType>::value, int> = 0>
  2273. BasicJsonType get() const
  2274. {
  2275. return *this;
  2276. }
  2277. /*!
  2278. @brief get a value (explicit)
  2279. Explicit type conversion between the JSON value and a compatible value
  2280. which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  2281. and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  2282. The value is converted by calling the @ref json_serializer<ValueType>
  2283. `from_json()` method.
  2284. The function is equivalent to executing
  2285. @code {.cpp}
  2286. ValueType ret;
  2287. JSONSerializer<ValueType>::from_json(*this, ret);
  2288. return ret;
  2289. @endcode
  2290. This overloads is chosen if:
  2291. - @a ValueType is not @ref basic_json,
  2292. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  2293. `void from_json(const basic_json&, ValueType&)`, and
  2294. - @ref json_serializer<ValueType> does not have a `from_json()` method of
  2295. the form `ValueType from_json(const basic_json&)`
  2296. @tparam ValueTypeCV the provided value type
  2297. @tparam ValueType the returned value type
  2298. @return copy of the JSON value, converted to @a ValueType
  2299. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  2300. @liveexample{The example below shows several conversions from JSON values
  2301. to other types. There a few things to note: (1) Floating-point numbers can
  2302. be converted to integers\, (2) A JSON array can be converted to a standard
  2303. `std::vector<short>`\, (3) A JSON object can be converted to C++
  2304. associative containers such as `std::unordered_map<std::string\,
  2305. json>`.,get__ValueType_const}
  2306. @since version 2.1.0
  2307. */
  2308. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  2309. detail::enable_if_t <
  2310. not detail::is_basic_json<ValueType>::value and
  2311. detail::has_from_json<basic_json_t, ValueType>::value and
  2312. not detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  2313. int> = 0>
  2314. ValueType get() const noexcept(noexcept(
  2315. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
  2316. {
  2317. // we cannot static_assert on ValueTypeCV being non-const, because
  2318. // there is support for get<const basic_json_t>(), which is why we
  2319. // still need the uncvref
  2320. static_assert(not std::is_reference<ValueTypeCV>::value,
  2321. "get() cannot be used with reference types, you might want to use get_ref()");
  2322. static_assert(std::is_default_constructible<ValueType>::value,
  2323. "types must be DefaultConstructible when used with get()");
  2324. ValueType ret;
  2325. JSONSerializer<ValueType>::from_json(*this, ret);
  2326. return ret;
  2327. }
  2328. /*!
  2329. @brief get a value (explicit); special case
  2330. Explicit type conversion between the JSON value and a compatible value
  2331. which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  2332. and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  2333. The value is converted by calling the @ref json_serializer<ValueType>
  2334. `from_json()` method.
  2335. The function is equivalent to executing
  2336. @code {.cpp}
  2337. return JSONSerializer<ValueTypeCV>::from_json(*this);
  2338. @endcode
  2339. This overloads is chosen if:
  2340. - @a ValueType is not @ref basic_json and
  2341. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  2342. `ValueType from_json(const basic_json&)`
  2343. @note If @ref json_serializer<ValueType> has both overloads of
  2344. `from_json()`, this one is chosen.
  2345. @tparam ValueTypeCV the provided value type
  2346. @tparam ValueType the returned value type
  2347. @return copy of the JSON value, converted to @a ValueType
  2348. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  2349. @since version 2.1.0
  2350. */
  2351. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  2352. detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and
  2353. detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  2354. int> = 0>
  2355. ValueType get() const noexcept(noexcept(
  2356. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>())))
  2357. {
  2358. static_assert(not std::is_reference<ValueTypeCV>::value,
  2359. "get() cannot be used with reference types, you might want to use get_ref()");
  2360. return JSONSerializer<ValueType>::from_json(*this);
  2361. }
  2362. /*!
  2363. @brief get a value (explicit)
  2364. Explicit type conversion between the JSON value and a compatible value.
  2365. The value is filled into the input parameter by calling the @ref json_serializer<ValueType>
  2366. `from_json()` method.
  2367. The function is equivalent to executing
  2368. @code {.cpp}
  2369. ValueType v;
  2370. JSONSerializer<ValueType>::from_json(*this, v);
  2371. @endcode
  2372. This overloads is chosen if:
  2373. - @a ValueType is not @ref basic_json,
  2374. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  2375. `void from_json(const basic_json&, ValueType&)`, and
  2376. @tparam ValueType the input parameter type.
  2377. @return the input parameter, allowing chaining calls.
  2378. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  2379. @liveexample{The example below shows several conversions from JSON values
  2380. to other types. There a few things to note: (1) Floating-point numbers can
  2381. be converted to integers\, (2) A JSON array can be converted to a standard
  2382. `std::vector<short>`\, (3) A JSON object can be converted to C++
  2383. associative containers such as `std::unordered_map<std::string\,
  2384. json>`.,get_to}
  2385. @since version 3.3.0
  2386. */
  2387. template<typename ValueType,
  2388. detail::enable_if_t <
  2389. not detail::is_basic_json<ValueType>::value and
  2390. detail::has_from_json<basic_json_t, ValueType>::value,
  2391. int> = 0>
  2392. ValueType & get_to(ValueType& v) const noexcept(noexcept(
  2393. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v)))
  2394. {
  2395. JSONSerializer<ValueType>::from_json(*this, v);
  2396. return v;
  2397. }
  2398. template <
  2399. typename T, std::size_t N,
  2400. typename Array = T (&)[N],
  2401. detail::enable_if_t <
  2402. detail::has_from_json<basic_json_t, Array>::value, int > = 0 >
  2403. Array get_to(T (&v)[N]) const
  2404. noexcept(noexcept(JSONSerializer<Array>::from_json(
  2405. std::declval<const basic_json_t&>(), v)))
  2406. {
  2407. JSONSerializer<Array>::from_json(*this, v);
  2408. return v;
  2409. }
  2410. /*!
  2411. @brief get a pointer value (implicit)
  2412. Implicit pointer access to the internally stored JSON value. No copies are
  2413. made.
  2414. @warning Writing data to the pointee of the result yields an undefined
  2415. state.
  2416. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  2417. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  2418. @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
  2419. assertion.
  2420. @return pointer to the internally stored JSON value if the requested
  2421. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  2422. @complexity Constant.
  2423. @liveexample{The example below shows how pointers to internal values of a
  2424. JSON value can be requested. Note that no type conversions are made and a
  2425. `nullptr` is returned if the value and the requested pointer type does not
  2426. match.,get_ptr}
  2427. @since version 1.0.0
  2428. */
  2429. template<typename PointerType, typename std::enable_if<
  2430. std::is_pointer<PointerType>::value, int>::type = 0>
  2431. auto get_ptr() noexcept -> decltype(std::declval<basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  2432. {
  2433. // delegate the call to get_impl_ptr<>()
  2434. return get_impl_ptr(static_cast<PointerType>(nullptr));
  2435. }
  2436. /*!
  2437. @brief get a pointer value (implicit)
  2438. @copydoc get_ptr()
  2439. */
  2440. template<typename PointerType, typename std::enable_if<
  2441. std::is_pointer<PointerType>::value and
  2442. std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>
  2443. constexpr auto get_ptr() const noexcept -> decltype(std::declval<const basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  2444. {
  2445. // delegate the call to get_impl_ptr<>() const
  2446. return get_impl_ptr(static_cast<PointerType>(nullptr));
  2447. }
  2448. /*!
  2449. @brief get a pointer value (explicit)
  2450. Explicit pointer access to the internally stored JSON value. No copies are
  2451. made.
  2452. @warning The pointer becomes invalid if the underlying JSON object
  2453. changes.
  2454. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  2455. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  2456. @ref number_unsigned_t, or @ref number_float_t.
  2457. @return pointer to the internally stored JSON value if the requested
  2458. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  2459. @complexity Constant.
  2460. @liveexample{The example below shows how pointers to internal values of a
  2461. JSON value can be requested. Note that no type conversions are made and a
  2462. `nullptr` is returned if the value and the requested pointer type does not
  2463. match.,get__PointerType}
  2464. @sa @ref get_ptr() for explicit pointer-member access
  2465. @since version 1.0.0
  2466. */
  2467. template<typename PointerType, typename std::enable_if<
  2468. std::is_pointer<PointerType>::value, int>::type = 0>
  2469. auto get() noexcept -> decltype(std::declval<basic_json_t&>().template get_ptr<PointerType>())
  2470. {
  2471. // delegate the call to get_ptr
  2472. return get_ptr<PointerType>();
  2473. }
  2474. /*!
  2475. @brief get a pointer value (explicit)
  2476. @copydoc get()
  2477. */
  2478. template<typename PointerType, typename std::enable_if<
  2479. std::is_pointer<PointerType>::value, int>::type = 0>
  2480. constexpr auto get() const noexcept -> decltype(std::declval<const basic_json_t&>().template get_ptr<PointerType>())
  2481. {
  2482. // delegate the call to get_ptr
  2483. return get_ptr<PointerType>();
  2484. }
  2485. /*!
  2486. @brief get a reference value (implicit)
  2487. Implicit reference access to the internally stored JSON value. No copies
  2488. are made.
  2489. @warning Writing data to the referee of the result yields an undefined
  2490. state.
  2491. @tparam ReferenceType reference type; must be a reference to @ref array_t,
  2492. @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
  2493. @ref number_float_t. Enforced by static assertion.
  2494. @return reference to the internally stored JSON value if the requested
  2495. reference type @a ReferenceType fits to the JSON value; throws
  2496. type_error.303 otherwise
  2497. @throw type_error.303 in case passed type @a ReferenceType is incompatible
  2498. with the stored JSON value; see example below
  2499. @complexity Constant.
  2500. @liveexample{The example shows several calls to `get_ref()`.,get_ref}
  2501. @since version 1.1.0
  2502. */
  2503. template<typename ReferenceType, typename std::enable_if<
  2504. std::is_reference<ReferenceType>::value, int>::type = 0>
  2505. ReferenceType get_ref()
  2506. {
  2507. // delegate call to get_ref_impl
  2508. return get_ref_impl<ReferenceType>(*this);
  2509. }
  2510. /*!
  2511. @brief get a reference value (implicit)
  2512. @copydoc get_ref()
  2513. */
  2514. template<typename ReferenceType, typename std::enable_if<
  2515. std::is_reference<ReferenceType>::value and
  2516. std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0>
  2517. ReferenceType get_ref() const
  2518. {
  2519. // delegate call to get_ref_impl
  2520. return get_ref_impl<ReferenceType>(*this);
  2521. }
  2522. /*!
  2523. @brief get a value (implicit)
  2524. Implicit type conversion between the JSON value and a compatible value.
  2525. The call is realized by calling @ref get() const.
  2526. @tparam ValueType non-pointer type compatible to the JSON value, for
  2527. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  2528. `std::vector` types for JSON arrays. The character type of @ref string_t
  2529. as well as an initializer list of this type is excluded to avoid
  2530. ambiguities as these types implicitly convert to `std::string`.
  2531. @return copy of the JSON value, converted to type @a ValueType
  2532. @throw type_error.302 in case passed type @a ValueType is incompatible
  2533. to the JSON value type (e.g., the JSON value is of type boolean, but a
  2534. string is requested); see example below
  2535. @complexity Linear in the size of the JSON value.
  2536. @liveexample{The example below shows several conversions from JSON values
  2537. to other types. There a few things to note: (1) Floating-point numbers can
  2538. be converted to integers\, (2) A JSON array can be converted to a standard
  2539. `std::vector<short>`\, (3) A JSON object can be converted to C++
  2540. associative containers such as `std::unordered_map<std::string\,
  2541. json>`.,operator__ValueType}
  2542. @since version 1.0.0
  2543. */
  2544. template < typename ValueType, typename std::enable_if <
  2545. not std::is_pointer<ValueType>::value and
  2546. not std::is_same<ValueType, detail::json_ref<basic_json>>::value and
  2547. not std::is_same<ValueType, typename string_t::value_type>::value and
  2548. not detail::is_basic_json<ValueType>::value
  2549. and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
  2550. #if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) and _MSC_VER >= 1910 and _MSC_VER <= 1914))
  2551. and not std::is_same<ValueType, typename std::string_view>::value
  2552. #endif
  2553. and detail::is_detected<detail::get_template_function, const basic_json_t&, ValueType>::value
  2554. , int >::type = 0 >
  2555. operator ValueType() const
  2556. {
  2557. // delegate the call to get<>() const
  2558. return get<ValueType>();
  2559. }
  2560. /*!
  2561. @return reference to the binary value
  2562. @throw type_error.302 if the value is not binary
  2563. @sa @ref is_binary() to check if the value is binary
  2564. @since version 3.8.0
  2565. */
  2566. binary_t& get_binary()
  2567. {
  2568. if (not is_binary())
  2569. {
  2570. JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name())));
  2571. }
  2572. return *get_ptr<binary_t*>();
  2573. }
  2574. /// @copydoc get_binary()
  2575. const binary_t& get_binary() const
  2576. {
  2577. if (not is_binary())
  2578. {
  2579. JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name())));
  2580. }
  2581. return *get_ptr<const binary_t*>();
  2582. }
  2583. /// @}
  2584. ////////////////////
  2585. // element access //
  2586. ////////////////////
  2587. /// @name element access
  2588. /// Access to the JSON value.
  2589. /// @{
  2590. /*!
  2591. @brief access specified array element with bounds checking
  2592. Returns a reference to the element at specified location @a idx, with
  2593. bounds checking.
  2594. @param[in] idx index of the element to access
  2595. @return reference to the element at index @a idx
  2596. @throw type_error.304 if the JSON value is not an array; in this case,
  2597. calling `at` with an index makes no sense. See example below.
  2598. @throw out_of_range.401 if the index @a idx is out of range of the array;
  2599. that is, `idx >= size()`. See example below.
  2600. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  2601. changes in the JSON value.
  2602. @complexity Constant.
  2603. @since version 1.0.0
  2604. @liveexample{The example below shows how array elements can be read and
  2605. written using `at()`. It also demonstrates the different exceptions that
  2606. can be thrown.,at__size_type}
  2607. */
  2608. reference at(size_type idx)
  2609. {
  2610. // at only works for arrays
  2611. if (JSON_HEDLEY_LIKELY(is_array()))
  2612. {
  2613. JSON_TRY
  2614. {
  2615. return m_value.array->at(idx);
  2616. }
  2617. JSON_CATCH (std::out_of_range&)
  2618. {
  2619. // create better exception explanation
  2620. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  2621. }
  2622. }
  2623. else
  2624. {
  2625. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  2626. }
  2627. }
  2628. /*!
  2629. @brief access specified array element with bounds checking
  2630. Returns a const reference to the element at specified location @a idx,
  2631. with bounds checking.
  2632. @param[in] idx index of the element to access
  2633. @return const reference to the element at index @a idx
  2634. @throw type_error.304 if the JSON value is not an array; in this case,
  2635. calling `at` with an index makes no sense. See example below.
  2636. @throw out_of_range.401 if the index @a idx is out of range of the array;
  2637. that is, `idx >= size()`. See example below.
  2638. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  2639. changes in the JSON value.
  2640. @complexity Constant.
  2641. @since version 1.0.0
  2642. @liveexample{The example below shows how array elements can be read using
  2643. `at()`. It also demonstrates the different exceptions that can be thrown.,
  2644. at__size_type_const}
  2645. */
  2646. const_reference at(size_type idx) const
  2647. {
  2648. // at only works for arrays
  2649. if (JSON_HEDLEY_LIKELY(is_array()))
  2650. {
  2651. JSON_TRY
  2652. {
  2653. return m_value.array->at(idx);
  2654. }
  2655. JSON_CATCH (std::out_of_range&)
  2656. {
  2657. // create better exception explanation
  2658. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  2659. }
  2660. }
  2661. else
  2662. {
  2663. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  2664. }
  2665. }
  2666. /*!
  2667. @brief access specified object element with bounds checking
  2668. Returns a reference to the element at with specified key @a key, with
  2669. bounds checking.
  2670. @param[in] key key of the element to access
  2671. @return reference to the element at key @a key
  2672. @throw type_error.304 if the JSON value is not an object; in this case,
  2673. calling `at` with a key makes no sense. See example below.
  2674. @throw out_of_range.403 if the key @a key is is not stored in the object;
  2675. that is, `find(key) == end()`. See example below.
  2676. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  2677. changes in the JSON value.
  2678. @complexity Logarithmic in the size of the container.
  2679. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  2680. access by reference
  2681. @sa @ref value() for access by value with a default value
  2682. @since version 1.0.0
  2683. @liveexample{The example below shows how object elements can be read and
  2684. written using `at()`. It also demonstrates the different exceptions that
  2685. can be thrown.,at__object_t_key_type}
  2686. */
  2687. reference at(const typename object_t::key_type& key)
  2688. {
  2689. // at only works for objects
  2690. if (JSON_HEDLEY_LIKELY(is_object()))
  2691. {
  2692. JSON_TRY
  2693. {
  2694. return m_value.object->at(key);
  2695. }
  2696. JSON_CATCH (std::out_of_range&)
  2697. {
  2698. // create better exception explanation
  2699. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  2700. }
  2701. }
  2702. else
  2703. {
  2704. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  2705. }
  2706. }
  2707. /*!
  2708. @brief access specified object element with bounds checking
  2709. Returns a const reference to the element at with specified key @a key,
  2710. with bounds checking.
  2711. @param[in] key key of the element to access
  2712. @return const reference to the element at key @a key
  2713. @throw type_error.304 if the JSON value is not an object; in this case,
  2714. calling `at` with a key makes no sense. See example below.
  2715. @throw out_of_range.403 if the key @a key is is not stored in the object;
  2716. that is, `find(key) == end()`. See example below.
  2717. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  2718. changes in the JSON value.
  2719. @complexity Logarithmic in the size of the container.
  2720. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  2721. access by reference
  2722. @sa @ref value() for access by value with a default value
  2723. @since version 1.0.0
  2724. @liveexample{The example below shows how object elements can be read using
  2725. `at()`. It also demonstrates the different exceptions that can be thrown.,
  2726. at__object_t_key_type_const}
  2727. */
  2728. const_reference at(const typename object_t::key_type& key) const
  2729. {
  2730. // at only works for objects
  2731. if (JSON_HEDLEY_LIKELY(is_object()))
  2732. {
  2733. JSON_TRY
  2734. {
  2735. return m_value.object->at(key);
  2736. }
  2737. JSON_CATCH (std::out_of_range&)
  2738. {
  2739. // create better exception explanation
  2740. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  2741. }
  2742. }
  2743. else
  2744. {
  2745. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  2746. }
  2747. }
  2748. /*!
  2749. @brief access specified array element
  2750. Returns a reference to the element at specified location @a idx.
  2751. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
  2752. then the array is silently filled up with `null` values to make `idx` a
  2753. valid reference to the last stored element.
  2754. @param[in] idx index of the element to access
  2755. @return reference to the element at index @a idx
  2756. @throw type_error.305 if the JSON value is not an array or null; in that
  2757. cases, using the [] operator with an index makes no sense.
  2758. @complexity Constant if @a idx is in the range of the array. Otherwise
  2759. linear in `idx - size()`.
  2760. @liveexample{The example below shows how array elements can be read and
  2761. written using `[]` operator. Note the addition of `null`
  2762. values.,operatorarray__size_type}
  2763. @since version 1.0.0
  2764. */
  2765. reference operator[](size_type idx)
  2766. {
  2767. // implicitly convert null value to an empty array
  2768. if (is_null())
  2769. {
  2770. m_type = value_t::array;
  2771. m_value.array = create<array_t>();
  2772. assert_invariant();
  2773. }
  2774. // operator[] only works for arrays
  2775. if (JSON_HEDLEY_LIKELY(is_array()))
  2776. {
  2777. // fill up array with null values if given idx is outside range
  2778. if (idx >= m_value.array->size())
  2779. {
  2780. m_value.array->insert(m_value.array->end(),
  2781. idx - m_value.array->size() + 1,
  2782. basic_json());
  2783. }
  2784. return m_value.array->operator[](idx);
  2785. }
  2786. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
  2787. }
  2788. /*!
  2789. @brief access specified array element
  2790. Returns a const reference to the element at specified location @a idx.
  2791. @param[in] idx index of the element to access
  2792. @return const reference to the element at index @a idx
  2793. @throw type_error.305 if the JSON value is not an array; in that case,
  2794. using the [] operator with an index makes no sense.
  2795. @complexity Constant.
  2796. @liveexample{The example below shows how array elements can be read using
  2797. the `[]` operator.,operatorarray__size_type_const}
  2798. @since version 1.0.0
  2799. */
  2800. const_reference operator[](size_type idx) const
  2801. {
  2802. // const operator[] only works for arrays
  2803. if (JSON_HEDLEY_LIKELY(is_array()))
  2804. {
  2805. return m_value.array->operator[](idx);
  2806. }
  2807. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
  2808. }
  2809. /*!
  2810. @brief access specified object element
  2811. Returns a reference to the element at with specified key @a key.
  2812. @note If @a key is not found in the object, then it is silently added to
  2813. the object and filled with a `null` value to make `key` a valid reference.
  2814. In case the value was `null` before, it is converted to an object.
  2815. @param[in] key key of the element to access
  2816. @return reference to the element at key @a key
  2817. @throw type_error.305 if the JSON value is not an object or null; in that
  2818. cases, using the [] operator with a key makes no sense.
  2819. @complexity Logarithmic in the size of the container.
  2820. @liveexample{The example below shows how object elements can be read and
  2821. written using the `[]` operator.,operatorarray__key_type}
  2822. @sa @ref at(const typename object_t::key_type&) for access by reference
  2823. with range checking
  2824. @sa @ref value() for access by value with a default value
  2825. @since version 1.0.0
  2826. */
  2827. reference operator[](const typename object_t::key_type& key)
  2828. {
  2829. // implicitly convert null value to an empty object
  2830. if (is_null())
  2831. {
  2832. m_type = value_t::object;
  2833. m_value.object = create<object_t>();
  2834. assert_invariant();
  2835. }
  2836. // operator[] only works for objects
  2837. if (JSON_HEDLEY_LIKELY(is_object()))
  2838. {
  2839. return m_value.object->operator[](key);
  2840. }
  2841. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  2842. }
  2843. /*!
  2844. @brief read-only access specified object element
  2845. Returns a const reference to the element at with specified key @a key. No
  2846. bounds checking is performed.
  2847. @warning If the element with key @a key does not exist, the behavior is
  2848. undefined.
  2849. @param[in] key key of the element to access
  2850. @return const reference to the element at key @a key
  2851. @pre The element with key @a key must exist. **This precondition is
  2852. enforced with an assertion.**
  2853. @throw type_error.305 if the JSON value is not an object; in that case,
  2854. using the [] operator with a key makes no sense.
  2855. @complexity Logarithmic in the size of the container.
  2856. @liveexample{The example below shows how object elements can be read using
  2857. the `[]` operator.,operatorarray__key_type_const}
  2858. @sa @ref at(const typename object_t::key_type&) for access by reference
  2859. with range checking
  2860. @sa @ref value() for access by value with a default value
  2861. @since version 1.0.0
  2862. */
  2863. const_reference operator[](const typename object_t::key_type& key) const
  2864. {
  2865. // const operator[] only works for objects
  2866. if (JSON_HEDLEY_LIKELY(is_object()))
  2867. {
  2868. assert(m_value.object->find(key) != m_value.object->end());
  2869. return m_value.object->find(key)->second;
  2870. }
  2871. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  2872. }
  2873. /*!
  2874. @brief access specified object element
  2875. Returns a reference to the element at with specified key @a key.
  2876. @note If @a key is not found in the object, then it is silently added to
  2877. the object and filled with a `null` value to make `key` a valid reference.
  2878. In case the value was `null` before, it is converted to an object.
  2879. @param[in] key key of the element to access
  2880. @return reference to the element at key @a key
  2881. @throw type_error.305 if the JSON value is not an object or null; in that
  2882. cases, using the [] operator with a key makes no sense.
  2883. @complexity Logarithmic in the size of the container.
  2884. @liveexample{The example below shows how object elements can be read and
  2885. written using the `[]` operator.,operatorarray__key_type}
  2886. @sa @ref at(const typename object_t::key_type&) for access by reference
  2887. with range checking
  2888. @sa @ref value() for access by value with a default value
  2889. @since version 1.1.0
  2890. */
  2891. template<typename T>
  2892. JSON_HEDLEY_NON_NULL(2)
  2893. reference operator[](T* key)
  2894. {
  2895. // implicitly convert null to object
  2896. if (is_null())
  2897. {
  2898. m_type = value_t::object;
  2899. m_value = value_t::object;
  2900. assert_invariant();
  2901. }
  2902. // at only works for objects
  2903. if (JSON_HEDLEY_LIKELY(is_object()))
  2904. {
  2905. return m_value.object->operator[](key);
  2906. }
  2907. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  2908. }
  2909. /*!
  2910. @brief read-only access specified object element
  2911. Returns a const reference to the element at with specified key @a key. No
  2912. bounds checking is performed.
  2913. @warning If the element with key @a key does not exist, the behavior is
  2914. undefined.
  2915. @param[in] key key of the element to access
  2916. @return const reference to the element at key @a key
  2917. @pre The element with key @a key must exist. **This precondition is
  2918. enforced with an assertion.**
  2919. @throw type_error.305 if the JSON value is not an object; in that case,
  2920. using the [] operator with a key makes no sense.
  2921. @complexity Logarithmic in the size of the container.
  2922. @liveexample{The example below shows how object elements can be read using
  2923. the `[]` operator.,operatorarray__key_type_const}
  2924. @sa @ref at(const typename object_t::key_type&) for access by reference
  2925. with range checking
  2926. @sa @ref value() for access by value with a default value
  2927. @since version 1.1.0
  2928. */
  2929. template<typename T>
  2930. JSON_HEDLEY_NON_NULL(2)
  2931. const_reference operator[](T* key) const
  2932. {
  2933. // at only works for objects
  2934. if (JSON_HEDLEY_LIKELY(is_object()))
  2935. {
  2936. assert(m_value.object->find(key) != m_value.object->end());
  2937. return m_value.object->find(key)->second;
  2938. }
  2939. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  2940. }
  2941. /*!
  2942. @brief access specified object element with default value
  2943. Returns either a copy of an object's element at the specified key @a key
  2944. or a given default value if no element with key @a key exists.
  2945. The function is basically equivalent to executing
  2946. @code {.cpp}
  2947. try {
  2948. return at(key);
  2949. } catch(out_of_range) {
  2950. return default_value;
  2951. }
  2952. @endcode
  2953. @note Unlike @ref at(const typename object_t::key_type&), this function
  2954. does not throw if the given key @a key was not found.
  2955. @note Unlike @ref operator[](const typename object_t::key_type& key), this
  2956. function does not implicitly add an element to the position defined by @a
  2957. key. This function is furthermore also applicable to const objects.
  2958. @param[in] key key of the element to access
  2959. @param[in] default_value the value to return if @a key is not found
  2960. @tparam ValueType type compatible to JSON values, for instance `int` for
  2961. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  2962. JSON arrays. Note the type of the expected value at @a key and the default
  2963. value @a default_value must be compatible.
  2964. @return copy of the element at key @a key or @a default_value if @a key
  2965. is not found
  2966. @throw type_error.302 if @a default_value does not match the type of the
  2967. value at @a key
  2968. @throw type_error.306 if the JSON value is not an object; in that case,
  2969. using `value()` with a key makes no sense.
  2970. @complexity Logarithmic in the size of the container.
  2971. @liveexample{The example below shows how object elements can be queried
  2972. with a default value.,basic_json__value}
  2973. @sa @ref at(const typename object_t::key_type&) for access by reference
  2974. with range checking
  2975. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  2976. access by reference
  2977. @since version 1.0.0
  2978. */
  2979. template<class ValueType, typename std::enable_if<
  2980. std::is_convertible<basic_json_t, ValueType>::value
  2981. and not std::is_same<value_t, ValueType>::value, int>::type = 0>
  2982. ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
  2983. {
  2984. // at only works for objects
  2985. if (JSON_HEDLEY_LIKELY(is_object()))
  2986. {
  2987. // if key is found, return value and given default value otherwise
  2988. const auto it = find(key);
  2989. if (it != end())
  2990. {
  2991. return *it;
  2992. }
  2993. return default_value;
  2994. }
  2995. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  2996. }
  2997. /*!
  2998. @brief overload for a default value of type const char*
  2999. @copydoc basic_json::value(const typename object_t::key_type&, const ValueType&) const
  3000. */
  3001. string_t value(const typename object_t::key_type& key, const char* default_value) const
  3002. {
  3003. return value(key, string_t(default_value));
  3004. }
  3005. /*!
  3006. @brief access specified object element via JSON Pointer with default value
  3007. Returns either a copy of an object's element at the specified key @a key
  3008. or a given default value if no element with key @a key exists.
  3009. The function is basically equivalent to executing
  3010. @code {.cpp}
  3011. try {
  3012. return at(ptr);
  3013. } catch(out_of_range) {
  3014. return default_value;
  3015. }
  3016. @endcode
  3017. @note Unlike @ref at(const json_pointer&), this function does not throw
  3018. if the given key @a key was not found.
  3019. @param[in] ptr a JSON pointer to the element to access
  3020. @param[in] default_value the value to return if @a ptr found no value
  3021. @tparam ValueType type compatible to JSON values, for instance `int` for
  3022. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  3023. JSON arrays. Note the type of the expected value at @a key and the default
  3024. value @a default_value must be compatible.
  3025. @return copy of the element at key @a key or @a default_value if @a key
  3026. is not found
  3027. @throw type_error.302 if @a default_value does not match the type of the
  3028. value at @a ptr
  3029. @throw type_error.306 if the JSON value is not an object; in that case,
  3030. using `value()` with a key makes no sense.
  3031. @complexity Logarithmic in the size of the container.
  3032. @liveexample{The example below shows how object elements can be queried
  3033. with a default value.,basic_json__value_ptr}
  3034. @sa @ref operator[](const json_pointer&) for unchecked access by reference
  3035. @since version 2.0.2
  3036. */
  3037. template<class ValueType, typename std::enable_if<
  3038. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  3039. ValueType value(const json_pointer& ptr, const ValueType& default_value) const
  3040. {
  3041. // at only works for objects
  3042. if (JSON_HEDLEY_LIKELY(is_object()))
  3043. {
  3044. // if pointer resolves a value, return it or use default value
  3045. JSON_TRY
  3046. {
  3047. return ptr.get_checked(this);
  3048. }
  3049. JSON_INTERNAL_CATCH (out_of_range&)
  3050. {
  3051. return default_value;
  3052. }
  3053. }
  3054. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  3055. }
  3056. /*!
  3057. @brief overload for a default value of type const char*
  3058. @copydoc basic_json::value(const json_pointer&, ValueType) const
  3059. */
  3060. JSON_HEDLEY_NON_NULL(3)
  3061. string_t value(const json_pointer& ptr, const char* default_value) const
  3062. {
  3063. return value(ptr, string_t(default_value));
  3064. }
  3065. /*!
  3066. @brief access the first element
  3067. Returns a reference to the first element in the container. For a JSON
  3068. container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
  3069. @return In case of a structured type (array or object), a reference to the
  3070. first element is returned. In case of number, string, boolean, or binary
  3071. values, a reference to the value is returned.
  3072. @complexity Constant.
  3073. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  3074. or an empty array or object (undefined behavior, **guarded by
  3075. assertions**).
  3076. @post The JSON value remains unchanged.
  3077. @throw invalid_iterator.214 when called on `null` value
  3078. @liveexample{The following code shows an example for `front()`.,front}
  3079. @sa @ref back() -- access the last element
  3080. @since version 1.0.0
  3081. */
  3082. reference front()
  3083. {
  3084. return *begin();
  3085. }
  3086. /*!
  3087. @copydoc basic_json::front()
  3088. */
  3089. const_reference front() const
  3090. {
  3091. return *cbegin();
  3092. }
  3093. /*!
  3094. @brief access the last element
  3095. Returns a reference to the last element in the container. For a JSON
  3096. container `c`, the expression `c.back()` is equivalent to
  3097. @code {.cpp}
  3098. auto tmp = c.end();
  3099. --tmp;
  3100. return *tmp;
  3101. @endcode
  3102. @return In case of a structured type (array or object), a reference to the
  3103. last element is returned. In case of number, string, boolean, or binary
  3104. values, a reference to the value is returned.
  3105. @complexity Constant.
  3106. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  3107. or an empty array or object (undefined behavior, **guarded by
  3108. assertions**).
  3109. @post The JSON value remains unchanged.
  3110. @throw invalid_iterator.214 when called on a `null` value. See example
  3111. below.
  3112. @liveexample{The following code shows an example for `back()`.,back}
  3113. @sa @ref front() -- access the first element
  3114. @since version 1.0.0
  3115. */
  3116. reference back()
  3117. {
  3118. auto tmp = end();
  3119. --tmp;
  3120. return *tmp;
  3121. }
  3122. /*!
  3123. @copydoc basic_json::back()
  3124. */
  3125. const_reference back() const
  3126. {
  3127. auto tmp = cend();
  3128. --tmp;
  3129. return *tmp;
  3130. }
  3131. /*!
  3132. @brief remove element given an iterator
  3133. Removes the element specified by iterator @a pos. The iterator @a pos must
  3134. be valid and dereferenceable. Thus the `end()` iterator (which is valid,
  3135. but is not dereferenceable) cannot be used as a value for @a pos.
  3136. If called on a primitive type other than `null`, the resulting JSON value
  3137. will be `null`.
  3138. @param[in] pos iterator to the element to remove
  3139. @return Iterator following the last removed element. If the iterator @a
  3140. pos refers to the last element, the `end()` iterator is returned.
  3141. @tparam IteratorType an @ref iterator or @ref const_iterator
  3142. @post Invalidates iterators and references at or after the point of the
  3143. erase, including the `end()` iterator.
  3144. @throw type_error.307 if called on a `null` value; example: `"cannot use
  3145. erase() with null"`
  3146. @throw invalid_iterator.202 if called on an iterator which does not belong
  3147. to the current JSON value; example: `"iterator does not fit current
  3148. value"`
  3149. @throw invalid_iterator.205 if called on a primitive type with invalid
  3150. iterator (i.e., any iterator which is not `begin()`); example: `"iterator
  3151. out of range"`
  3152. @complexity The complexity depends on the type:
  3153. - objects: amortized constant
  3154. - arrays: linear in distance between @a pos and the end of the container
  3155. - strings and binary: linear in the length of the member
  3156. - other types: constant
  3157. @liveexample{The example shows the result of `erase()` for different JSON
  3158. types.,erase__IteratorType}
  3159. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  3160. the given range
  3161. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  3162. from an object at the given key
  3163. @sa @ref erase(const size_type) -- removes the element from an array at
  3164. the given index
  3165. @since version 1.0.0
  3166. */
  3167. template<class IteratorType, typename std::enable_if<
  3168. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  3169. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  3170. = 0>
  3171. IteratorType erase(IteratorType pos)
  3172. {
  3173. // make sure iterator fits the current value
  3174. if (JSON_HEDLEY_UNLIKELY(this != pos.m_object))
  3175. {
  3176. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  3177. }
  3178. IteratorType result = end();
  3179. switch (m_type)
  3180. {
  3181. case value_t::boolean:
  3182. case value_t::number_float:
  3183. case value_t::number_integer:
  3184. case value_t::number_unsigned:
  3185. case value_t::string:
  3186. case value_t::binary:
  3187. {
  3188. if (JSON_HEDLEY_UNLIKELY(not pos.m_it.primitive_iterator.is_begin()))
  3189. {
  3190. JSON_THROW(invalid_iterator::create(205, "iterator out of range"));
  3191. }
  3192. if (is_string())
  3193. {
  3194. AllocatorType<string_t> alloc;
  3195. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  3196. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  3197. m_value.string = nullptr;
  3198. }
  3199. else if (is_binary())
  3200. {
  3201. AllocatorType<binary_t> alloc;
  3202. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.binary);
  3203. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.binary, 1);
  3204. m_value.binary = nullptr;
  3205. }
  3206. m_type = value_t::null;
  3207. assert_invariant();
  3208. break;
  3209. }
  3210. case value_t::object:
  3211. {
  3212. result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
  3213. break;
  3214. }
  3215. case value_t::array:
  3216. {
  3217. result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
  3218. break;
  3219. }
  3220. default:
  3221. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  3222. }
  3223. return result;
  3224. }
  3225. /*!
  3226. @brief remove elements given an iterator range
  3227. Removes the element specified by the range `[first; last)`. The iterator
  3228. @a first does not need to be dereferenceable if `first == last`: erasing
  3229. an empty range is a no-op.
  3230. If called on a primitive type other than `null`, the resulting JSON value
  3231. will be `null`.
  3232. @param[in] first iterator to the beginning of the range to remove
  3233. @param[in] last iterator past the end of the range to remove
  3234. @return Iterator following the last removed element. If the iterator @a
  3235. second refers to the last element, the `end()` iterator is returned.
  3236. @tparam IteratorType an @ref iterator or @ref const_iterator
  3237. @post Invalidates iterators and references at or after the point of the
  3238. erase, including the `end()` iterator.
  3239. @throw type_error.307 if called on a `null` value; example: `"cannot use
  3240. erase() with null"`
  3241. @throw invalid_iterator.203 if called on iterators which does not belong
  3242. to the current JSON value; example: `"iterators do not fit current value"`
  3243. @throw invalid_iterator.204 if called on a primitive type with invalid
  3244. iterators (i.e., if `first != begin()` and `last != end()`); example:
  3245. `"iterators out of range"`
  3246. @complexity The complexity depends on the type:
  3247. - objects: `log(size()) + std::distance(first, last)`
  3248. - arrays: linear in the distance between @a first and @a last, plus linear
  3249. in the distance between @a last and end of the container
  3250. - strings and binary: linear in the length of the member
  3251. - other types: constant
  3252. @liveexample{The example shows the result of `erase()` for different JSON
  3253. types.,erase__IteratorType_IteratorType}
  3254. @sa @ref erase(IteratorType) -- removes the element at a given position
  3255. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  3256. from an object at the given key
  3257. @sa @ref erase(const size_type) -- removes the element from an array at
  3258. the given index
  3259. @since version 1.0.0
  3260. */
  3261. template<class IteratorType, typename std::enable_if<
  3262. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  3263. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  3264. = 0>
  3265. IteratorType erase(IteratorType first, IteratorType last)
  3266. {
  3267. // make sure iterator fits the current value
  3268. if (JSON_HEDLEY_UNLIKELY(this != first.m_object or this != last.m_object))
  3269. {
  3270. JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value"));
  3271. }
  3272. IteratorType result = end();
  3273. switch (m_type)
  3274. {
  3275. case value_t::boolean:
  3276. case value_t::number_float:
  3277. case value_t::number_integer:
  3278. case value_t::number_unsigned:
  3279. case value_t::string:
  3280. case value_t::binary:
  3281. {
  3282. if (JSON_HEDLEY_LIKELY(not first.m_it.primitive_iterator.is_begin()
  3283. or not last.m_it.primitive_iterator.is_end()))
  3284. {
  3285. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  3286. }
  3287. if (is_string())
  3288. {
  3289. AllocatorType<string_t> alloc;
  3290. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  3291. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  3292. m_value.string = nullptr;
  3293. }
  3294. else if (is_binary())
  3295. {
  3296. AllocatorType<binary_t> alloc;
  3297. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.binary);
  3298. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.binary, 1);
  3299. m_value.binary = nullptr;
  3300. }
  3301. m_type = value_t::null;
  3302. assert_invariant();
  3303. break;
  3304. }
  3305. case value_t::object:
  3306. {
  3307. result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
  3308. last.m_it.object_iterator);
  3309. break;
  3310. }
  3311. case value_t::array:
  3312. {
  3313. result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
  3314. last.m_it.array_iterator);
  3315. break;
  3316. }
  3317. default:
  3318. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  3319. }
  3320. return result;
  3321. }
  3322. /*!
  3323. @brief remove element from a JSON object given a key
  3324. Removes elements from a JSON object with the key value @a key.
  3325. @param[in] key value of the elements to remove
  3326. @return Number of elements removed. If @a ObjectType is the default
  3327. `std::map` type, the return value will always be `0` (@a key was not
  3328. found) or `1` (@a key was found).
  3329. @post References and iterators to the erased elements are invalidated.
  3330. Other references and iterators are not affected.
  3331. @throw type_error.307 when called on a type other than JSON object;
  3332. example: `"cannot use erase() with null"`
  3333. @complexity `log(size()) + count(key)`
  3334. @liveexample{The example shows the effect of `erase()`.,erase__key_type}
  3335. @sa @ref erase(IteratorType) -- removes the element at a given position
  3336. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  3337. the given range
  3338. @sa @ref erase(const size_type) -- removes the element from an array at
  3339. the given index
  3340. @since version 1.0.0
  3341. */
  3342. size_type erase(const typename object_t::key_type& key)
  3343. {
  3344. // this erase only works for objects
  3345. if (JSON_HEDLEY_LIKELY(is_object()))
  3346. {
  3347. return m_value.object->erase(key);
  3348. }
  3349. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  3350. }
  3351. /*!
  3352. @brief remove element from a JSON array given an index
  3353. Removes element from a JSON array at the index @a idx.
  3354. @param[in] idx index of the element to remove
  3355. @throw type_error.307 when called on a type other than JSON object;
  3356. example: `"cannot use erase() with null"`
  3357. @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
  3358. is out of range"`
  3359. @complexity Linear in distance between @a idx and the end of the container.
  3360. @liveexample{The example shows the effect of `erase()`.,erase__size_type}
  3361. @sa @ref erase(IteratorType) -- removes the element at a given position
  3362. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  3363. the given range
  3364. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  3365. from an object at the given key
  3366. @since version 1.0.0
  3367. */
  3368. void erase(const size_type idx)
  3369. {
  3370. // this erase only works for arrays
  3371. if (JSON_HEDLEY_LIKELY(is_array()))
  3372. {
  3373. if (JSON_HEDLEY_UNLIKELY(idx >= size()))
  3374. {
  3375. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  3376. }
  3377. m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
  3378. }
  3379. else
  3380. {
  3381. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  3382. }
  3383. }
  3384. /// @}
  3385. ////////////
  3386. // lookup //
  3387. ////////////
  3388. /// @name lookup
  3389. /// @{
  3390. /*!
  3391. @brief find an element in a JSON object
  3392. Finds an element in a JSON object with key equivalent to @a key. If the
  3393. element is not found or the JSON value is not an object, end() is
  3394. returned.
  3395. @note This method always returns @ref end() when executed on a JSON type
  3396. that is not an object.
  3397. @param[in] key key value of the element to search for.
  3398. @return Iterator to an element with key equivalent to @a key. If no such
  3399. element is found or the JSON value is not an object, past-the-end (see
  3400. @ref end()) iterator is returned.
  3401. @complexity Logarithmic in the size of the JSON object.
  3402. @liveexample{The example shows how `find()` is used.,find__key_type}
  3403. @sa @ref contains(KeyT&&) const -- checks whether a key exists
  3404. @since version 1.0.0
  3405. */
  3406. template<typename KeyT>
  3407. iterator find(KeyT&& key)
  3408. {
  3409. auto result = end();
  3410. if (is_object())
  3411. {
  3412. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  3413. }
  3414. return result;
  3415. }
  3416. /*!
  3417. @brief find an element in a JSON object
  3418. @copydoc find(KeyT&&)
  3419. */
  3420. template<typename KeyT>
  3421. const_iterator find(KeyT&& key) const
  3422. {
  3423. auto result = cend();
  3424. if (is_object())
  3425. {
  3426. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  3427. }
  3428. return result;
  3429. }
  3430. /*!
  3431. @brief returns the number of occurrences of a key in a JSON object
  3432. Returns the number of elements with key @a key. If ObjectType is the
  3433. default `std::map` type, the return value will always be `0` (@a key was
  3434. not found) or `1` (@a key was found).
  3435. @note This method always returns `0` when executed on a JSON type that is
  3436. not an object.
  3437. @param[in] key key value of the element to count
  3438. @return Number of elements with key @a key. If the JSON value is not an
  3439. object, the return value will be `0`.
  3440. @complexity Logarithmic in the size of the JSON object.
  3441. @liveexample{The example shows how `count()` is used.,count}
  3442. @since version 1.0.0
  3443. */
  3444. template<typename KeyT>
  3445. size_type count(KeyT&& key) const
  3446. {
  3447. // return 0 for all nonobject types
  3448. return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;
  3449. }
  3450. /*!
  3451. @brief check the existence of an element in a JSON object
  3452. Check whether an element exists in a JSON object with key equivalent to
  3453. @a key. If the element is not found or the JSON value is not an object,
  3454. false is returned.
  3455. @note This method always returns false when executed on a JSON type
  3456. that is not an object.
  3457. @param[in] key key value to check its existence.
  3458. @return true if an element with specified @a key exists. If no such
  3459. element with such key is found or the JSON value is not an object,
  3460. false is returned.
  3461. @complexity Logarithmic in the size of the JSON object.
  3462. @liveexample{The following code shows an example for `contains()`.,contains}
  3463. @sa @ref find(KeyT&&) -- returns an iterator to an object element
  3464. @sa @ref contains(const json_pointer&) const -- checks the existence for a JSON pointer
  3465. @since version 3.6.0
  3466. */
  3467. template<typename KeyT, typename std::enable_if<
  3468. not std::is_same<typename std::decay<KeyT>::type, json_pointer>::value, int>::type = 0>
  3469. bool contains(KeyT && key) const
  3470. {
  3471. return is_object() and m_value.object->find(std::forward<KeyT>(key)) != m_value.object->end();
  3472. }
  3473. /*!
  3474. @brief check the existence of an element in a JSON object given a JSON pointer
  3475. Check whether the given JSON pointer @a ptr can be resolved in the current
  3476. JSON value.
  3477. @note This method can be executed on any JSON value type.
  3478. @param[in] ptr JSON pointer to check its existence.
  3479. @return true if the JSON pointer can be resolved to a stored value, false
  3480. otherwise.
  3481. @post If `j.contains(ptr)` returns true, it is safe to call `j[ptr]`.
  3482. @throw parse_error.106 if an array index begins with '0'
  3483. @throw parse_error.109 if an array index was not a number
  3484. @complexity Logarithmic in the size of the JSON object.
  3485. @liveexample{The following code shows an example for `contains()`.,contains_json_pointer}
  3486. @sa @ref contains(KeyT &&) const -- checks the existence of a key
  3487. @since version 3.7.0
  3488. */
  3489. bool contains(const json_pointer& ptr) const
  3490. {
  3491. return ptr.contains(this);
  3492. }
  3493. /// @}
  3494. ///////////////
  3495. // iterators //
  3496. ///////////////
  3497. /// @name iterators
  3498. /// @{
  3499. /*!
  3500. @brief returns an iterator to the first element
  3501. Returns an iterator to the first element.
  3502. @image html range-begin-end.svg "Illustration from cppreference.com"
  3503. @return iterator to the first element
  3504. @complexity Constant.
  3505. @requirement This function helps `basic_json` satisfying the
  3506. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  3507. requirements:
  3508. - The complexity is constant.
  3509. @liveexample{The following code shows an example for `begin()`.,begin}
  3510. @sa @ref cbegin() -- returns a const iterator to the beginning
  3511. @sa @ref end() -- returns an iterator to the end
  3512. @sa @ref cend() -- returns a const iterator to the end
  3513. @since version 1.0.0
  3514. */
  3515. iterator begin() noexcept
  3516. {
  3517. iterator result(this);
  3518. result.set_begin();
  3519. return result;
  3520. }
  3521. /*!
  3522. @copydoc basic_json::cbegin()
  3523. */
  3524. const_iterator begin() const noexcept
  3525. {
  3526. return cbegin();
  3527. }
  3528. /*!
  3529. @brief returns a const iterator to the first element
  3530. Returns a const iterator to the first element.
  3531. @image html range-begin-end.svg "Illustration from cppreference.com"
  3532. @return const iterator to the first element
  3533. @complexity Constant.
  3534. @requirement This function helps `basic_json` satisfying the
  3535. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  3536. requirements:
  3537. - The complexity is constant.
  3538. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
  3539. @liveexample{The following code shows an example for `cbegin()`.,cbegin}
  3540. @sa @ref begin() -- returns an iterator to the beginning
  3541. @sa @ref end() -- returns an iterator to the end
  3542. @sa @ref cend() -- returns a const iterator to the end
  3543. @since version 1.0.0
  3544. */
  3545. const_iterator cbegin() const noexcept
  3546. {
  3547. const_iterator result(this);
  3548. result.set_begin();
  3549. return result;
  3550. }
  3551. /*!
  3552. @brief returns an iterator to one past the last element
  3553. Returns an iterator to one past the last element.
  3554. @image html range-begin-end.svg "Illustration from cppreference.com"
  3555. @return iterator one past the last element
  3556. @complexity Constant.
  3557. @requirement This function helps `basic_json` satisfying the
  3558. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  3559. requirements:
  3560. - The complexity is constant.
  3561. @liveexample{The following code shows an example for `end()`.,end}
  3562. @sa @ref cend() -- returns a const iterator to the end
  3563. @sa @ref begin() -- returns an iterator to the beginning
  3564. @sa @ref cbegin() -- returns a const iterator to the beginning
  3565. @since version 1.0.0
  3566. */
  3567. iterator end() noexcept
  3568. {
  3569. iterator result(this);
  3570. result.set_end();
  3571. return result;
  3572. }
  3573. /*!
  3574. @copydoc basic_json::cend()
  3575. */
  3576. const_iterator end() const noexcept
  3577. {
  3578. return cend();
  3579. }
  3580. /*!
  3581. @brief returns a const iterator to one past the last element
  3582. Returns a const iterator to one past the last element.
  3583. @image html range-begin-end.svg "Illustration from cppreference.com"
  3584. @return const iterator one past the last element
  3585. @complexity Constant.
  3586. @requirement This function helps `basic_json` satisfying the
  3587. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  3588. requirements:
  3589. - The complexity is constant.
  3590. - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
  3591. @liveexample{The following code shows an example for `cend()`.,cend}
  3592. @sa @ref end() -- returns an iterator to the end
  3593. @sa @ref begin() -- returns an iterator to the beginning
  3594. @sa @ref cbegin() -- returns a const iterator to the beginning
  3595. @since version 1.0.0
  3596. */
  3597. const_iterator cend() const noexcept
  3598. {
  3599. const_iterator result(this);
  3600. result.set_end();
  3601. return result;
  3602. }
  3603. /*!
  3604. @brief returns an iterator to the reverse-beginning
  3605. Returns an iterator to the reverse-beginning; that is, the last element.
  3606. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  3607. @complexity Constant.
  3608. @requirement This function helps `basic_json` satisfying the
  3609. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  3610. requirements:
  3611. - The complexity is constant.
  3612. - Has the semantics of `reverse_iterator(end())`.
  3613. @liveexample{The following code shows an example for `rbegin()`.,rbegin}
  3614. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  3615. @sa @ref rend() -- returns a reverse iterator to the end
  3616. @sa @ref crend() -- returns a const reverse iterator to the end
  3617. @since version 1.0.0
  3618. */
  3619. reverse_iterator rbegin() noexcept
  3620. {
  3621. return reverse_iterator(end());
  3622. }
  3623. /*!
  3624. @copydoc basic_json::crbegin()
  3625. */
  3626. const_reverse_iterator rbegin() const noexcept
  3627. {
  3628. return crbegin();
  3629. }
  3630. /*!
  3631. @brief returns an iterator to the reverse-end
  3632. Returns an iterator to the reverse-end; that is, one before the first
  3633. element.
  3634. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  3635. @complexity Constant.
  3636. @requirement This function helps `basic_json` satisfying the
  3637. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  3638. requirements:
  3639. - The complexity is constant.
  3640. - Has the semantics of `reverse_iterator(begin())`.
  3641. @liveexample{The following code shows an example for `rend()`.,rend}
  3642. @sa @ref crend() -- returns a const reverse iterator to the end
  3643. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  3644. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  3645. @since version 1.0.0
  3646. */
  3647. reverse_iterator rend() noexcept
  3648. {
  3649. return reverse_iterator(begin());
  3650. }
  3651. /*!
  3652. @copydoc basic_json::crend()
  3653. */
  3654. const_reverse_iterator rend() const noexcept
  3655. {
  3656. return crend();
  3657. }
  3658. /*!
  3659. @brief returns a const reverse iterator to the last element
  3660. Returns a const iterator to the reverse-beginning; that is, the last
  3661. element.
  3662. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  3663. @complexity Constant.
  3664. @requirement This function helps `basic_json` satisfying the
  3665. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  3666. requirements:
  3667. - The complexity is constant.
  3668. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
  3669. @liveexample{The following code shows an example for `crbegin()`.,crbegin}
  3670. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  3671. @sa @ref rend() -- returns a reverse iterator to the end
  3672. @sa @ref crend() -- returns a const reverse iterator to the end
  3673. @since version 1.0.0
  3674. */
  3675. const_reverse_iterator crbegin() const noexcept
  3676. {
  3677. return const_reverse_iterator(cend());
  3678. }
  3679. /*!
  3680. @brief returns a const reverse iterator to one before the first
  3681. Returns a const reverse iterator to the reverse-end; that is, one before
  3682. the first element.
  3683. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  3684. @complexity Constant.
  3685. @requirement This function helps `basic_json` satisfying the
  3686. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  3687. requirements:
  3688. - The complexity is constant.
  3689. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
  3690. @liveexample{The following code shows an example for `crend()`.,crend}
  3691. @sa @ref rend() -- returns a reverse iterator to the end
  3692. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  3693. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  3694. @since version 1.0.0
  3695. */
  3696. const_reverse_iterator crend() const noexcept
  3697. {
  3698. return const_reverse_iterator(cbegin());
  3699. }
  3700. public:
  3701. /*!
  3702. @brief wrapper to access iterator member functions in range-based for
  3703. This function allows to access @ref iterator::key() and @ref
  3704. iterator::value() during range-based for loops. In these loops, a
  3705. reference to the JSON values is returned, so there is no access to the
  3706. underlying iterator.
  3707. For loop without iterator_wrapper:
  3708. @code{cpp}
  3709. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  3710. {
  3711. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  3712. }
  3713. @endcode
  3714. Range-based for loop without iterator proxy:
  3715. @code{cpp}
  3716. for (auto it : j_object)
  3717. {
  3718. // "it" is of type json::reference and has no key() member
  3719. std::cout << "value: " << it << '\n';
  3720. }
  3721. @endcode
  3722. Range-based for loop with iterator proxy:
  3723. @code{cpp}
  3724. for (auto it : json::iterator_wrapper(j_object))
  3725. {
  3726. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  3727. }
  3728. @endcode
  3729. @note When iterating over an array, `key()` will return the index of the
  3730. element as string (see example).
  3731. @param[in] ref reference to a JSON value
  3732. @return iteration proxy object wrapping @a ref with an interface to use in
  3733. range-based for loops
  3734. @liveexample{The following code shows how the wrapper is used,iterator_wrapper}
  3735. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  3736. changes in the JSON value.
  3737. @complexity Constant.
  3738. @note The name of this function is not yet final and may change in the
  3739. future.
  3740. @deprecated This stream operator is deprecated and will be removed in
  3741. future 4.0.0 of the library. Please use @ref items() instead;
  3742. that is, replace `json::iterator_wrapper(j)` with `j.items()`.
  3743. */
  3744. JSON_HEDLEY_DEPRECATED(3.1.0)
  3745. static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept
  3746. {
  3747. return ref.items();
  3748. }
  3749. /*!
  3750. @copydoc iterator_wrapper(reference)
  3751. */
  3752. JSON_HEDLEY_DEPRECATED(3.1.0)
  3753. static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept
  3754. {
  3755. return ref.items();
  3756. }
  3757. /*!
  3758. @brief helper to access iterator member functions in range-based for
  3759. This function allows to access @ref iterator::key() and @ref
  3760. iterator::value() during range-based for loops. In these loops, a
  3761. reference to the JSON values is returned, so there is no access to the
  3762. underlying iterator.
  3763. For loop without `items()` function:
  3764. @code{cpp}
  3765. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  3766. {
  3767. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  3768. }
  3769. @endcode
  3770. Range-based for loop without `items()` function:
  3771. @code{cpp}
  3772. for (auto it : j_object)
  3773. {
  3774. // "it" is of type json::reference and has no key() member
  3775. std::cout << "value: " << it << '\n';
  3776. }
  3777. @endcode
  3778. Range-based for loop with `items()` function:
  3779. @code{cpp}
  3780. for (auto& el : j_object.items())
  3781. {
  3782. std::cout << "key: " << el.key() << ", value:" << el.value() << '\n';
  3783. }
  3784. @endcode
  3785. The `items()` function also allows to use
  3786. [structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding)
  3787. (C++17):
  3788. @code{cpp}
  3789. for (auto& [key, val] : j_object.items())
  3790. {
  3791. std::cout << "key: " << key << ", value:" << val << '\n';
  3792. }
  3793. @endcode
  3794. @note When iterating over an array, `key()` will return the index of the
  3795. element as string (see example). For primitive types (e.g., numbers),
  3796. `key()` returns an empty string.
  3797. @warning Using `items()` on temporary objects is dangerous. Make sure the
  3798. object's lifetime exeeds the iteration. See
  3799. <https://github.com/nlohmann/json/issues/2040> for more
  3800. information.
  3801. @return iteration proxy object wrapping @a ref with an interface to use in
  3802. range-based for loops
  3803. @liveexample{The following code shows how the function is used.,items}
  3804. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  3805. changes in the JSON value.
  3806. @complexity Constant.
  3807. @since version 3.1.0, structured bindings support since 3.5.0.
  3808. */
  3809. iteration_proxy<iterator> items() noexcept
  3810. {
  3811. return iteration_proxy<iterator>(*this);
  3812. }
  3813. /*!
  3814. @copydoc items()
  3815. */
  3816. iteration_proxy<const_iterator> items() const noexcept
  3817. {
  3818. return iteration_proxy<const_iterator>(*this);
  3819. }
  3820. /// @}
  3821. //////////////
  3822. // capacity //
  3823. //////////////
  3824. /// @name capacity
  3825. /// @{
  3826. /*!
  3827. @brief checks whether the container is empty.
  3828. Checks if a JSON value has no elements (i.e. whether its @ref size is `0`).
  3829. @return The return value depends on the different types and is
  3830. defined as follows:
  3831. Value type | return value
  3832. ----------- | -------------
  3833. null | `true`
  3834. boolean | `false`
  3835. string | `false`
  3836. number | `false`
  3837. binary | `false`
  3838. object | result of function `object_t::empty()`
  3839. array | result of function `array_t::empty()`
  3840. @liveexample{The following code uses `empty()` to check if a JSON
  3841. object contains any elements.,empty}
  3842. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  3843. the Container concept; that is, their `empty()` functions have constant
  3844. complexity.
  3845. @iterators No changes.
  3846. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  3847. @note This function does not return whether a string stored as JSON value
  3848. is empty - it returns whether the JSON container itself is empty which is
  3849. false in the case of a string.
  3850. @requirement This function helps `basic_json` satisfying the
  3851. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  3852. requirements:
  3853. - The complexity is constant.
  3854. - Has the semantics of `begin() == end()`.
  3855. @sa @ref size() -- returns the number of elements
  3856. @since version 1.0.0
  3857. */
  3858. bool empty() const noexcept
  3859. {
  3860. switch (m_type)
  3861. {
  3862. case value_t::null:
  3863. {
  3864. // null values are empty
  3865. return true;
  3866. }
  3867. case value_t::array:
  3868. {
  3869. // delegate call to array_t::empty()
  3870. return m_value.array->empty();
  3871. }
  3872. case value_t::object:
  3873. {
  3874. // delegate call to object_t::empty()
  3875. return m_value.object->empty();
  3876. }
  3877. default:
  3878. {
  3879. // all other types are nonempty
  3880. return false;
  3881. }
  3882. }
  3883. }
  3884. /*!
  3885. @brief returns the number of elements
  3886. Returns the number of elements in a JSON value.
  3887. @return The return value depends on the different types and is
  3888. defined as follows:
  3889. Value type | return value
  3890. ----------- | -------------
  3891. null | `0`
  3892. boolean | `1`
  3893. string | `1`
  3894. number | `1`
  3895. binary | `1`
  3896. object | result of function object_t::size()
  3897. array | result of function array_t::size()
  3898. @liveexample{The following code calls `size()` on the different value
  3899. types.,size}
  3900. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  3901. the Container concept; that is, their size() functions have constant
  3902. complexity.
  3903. @iterators No changes.
  3904. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  3905. @note This function does not return the length of a string stored as JSON
  3906. value - it returns the number of elements in the JSON value which is 1 in
  3907. the case of a string.
  3908. @requirement This function helps `basic_json` satisfying the
  3909. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  3910. requirements:
  3911. - The complexity is constant.
  3912. - Has the semantics of `std::distance(begin(), end())`.
  3913. @sa @ref empty() -- checks whether the container is empty
  3914. @sa @ref max_size() -- returns the maximal number of elements
  3915. @since version 1.0.0
  3916. */
  3917. size_type size() const noexcept
  3918. {
  3919. switch (m_type)
  3920. {
  3921. case value_t::null:
  3922. {
  3923. // null values are empty
  3924. return 0;
  3925. }
  3926. case value_t::array:
  3927. {
  3928. // delegate call to array_t::size()
  3929. return m_value.array->size();
  3930. }
  3931. case value_t::object:
  3932. {
  3933. // delegate call to object_t::size()
  3934. return m_value.object->size();
  3935. }
  3936. default:
  3937. {
  3938. // all other types have size 1
  3939. return 1;
  3940. }
  3941. }
  3942. }
  3943. /*!
  3944. @brief returns the maximum possible number of elements
  3945. Returns the maximum number of elements a JSON value is able to hold due to
  3946. system or library implementation limitations, i.e. `std::distance(begin(),
  3947. end())` for the JSON value.
  3948. @return The return value depends on the different types and is
  3949. defined as follows:
  3950. Value type | return value
  3951. ----------- | -------------
  3952. null | `0` (same as `size()`)
  3953. boolean | `1` (same as `size()`)
  3954. string | `1` (same as `size()`)
  3955. number | `1` (same as `size()`)
  3956. binary | `1` (same as `size()`)
  3957. object | result of function `object_t::max_size()`
  3958. array | result of function `array_t::max_size()`
  3959. @liveexample{The following code calls `max_size()` on the different value
  3960. types. Note the output is implementation specific.,max_size}
  3961. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  3962. the Container concept; that is, their `max_size()` functions have constant
  3963. complexity.
  3964. @iterators No changes.
  3965. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  3966. @requirement This function helps `basic_json` satisfying the
  3967. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  3968. requirements:
  3969. - The complexity is constant.
  3970. - Has the semantics of returning `b.size()` where `b` is the largest
  3971. possible JSON value.
  3972. @sa @ref size() -- returns the number of elements
  3973. @since version 1.0.0
  3974. */
  3975. size_type max_size() const noexcept
  3976. {
  3977. switch (m_type)
  3978. {
  3979. case value_t::array:
  3980. {
  3981. // delegate call to array_t::max_size()
  3982. return m_value.array->max_size();
  3983. }
  3984. case value_t::object:
  3985. {
  3986. // delegate call to object_t::max_size()
  3987. return m_value.object->max_size();
  3988. }
  3989. default:
  3990. {
  3991. // all other types have max_size() == size()
  3992. return size();
  3993. }
  3994. }
  3995. }
  3996. /// @}
  3997. ///////////////
  3998. // modifiers //
  3999. ///////////////
  4000. /// @name modifiers
  4001. /// @{
  4002. /*!
  4003. @brief clears the contents
  4004. Clears the content of a JSON value and resets it to the default value as
  4005. if @ref basic_json(value_t) would have been called with the current value
  4006. type from @ref type():
  4007. Value type | initial value
  4008. ----------- | -------------
  4009. null | `null`
  4010. boolean | `false`
  4011. string | `""`
  4012. number | `0`
  4013. binary | An empty byte vector
  4014. object | `{}`
  4015. array | `[]`
  4016. @post Has the same effect as calling
  4017. @code {.cpp}
  4018. *this = basic_json(type());
  4019. @endcode
  4020. @liveexample{The example below shows the effect of `clear()` to different
  4021. JSON types.,clear}
  4022. @complexity Linear in the size of the JSON value.
  4023. @iterators All iterators, pointers and references related to this container
  4024. are invalidated.
  4025. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  4026. @sa @ref basic_json(value_t) -- constructor that creates an object with the
  4027. same value than calling `clear()`
  4028. @since version 1.0.0
  4029. */
  4030. void clear() noexcept
  4031. {
  4032. switch (m_type)
  4033. {
  4034. case value_t::number_integer:
  4035. {
  4036. m_value.number_integer = 0;
  4037. break;
  4038. }
  4039. case value_t::number_unsigned:
  4040. {
  4041. m_value.number_unsigned = 0;
  4042. break;
  4043. }
  4044. case value_t::number_float:
  4045. {
  4046. m_value.number_float = 0.0;
  4047. break;
  4048. }
  4049. case value_t::boolean:
  4050. {
  4051. m_value.boolean = false;
  4052. break;
  4053. }
  4054. case value_t::string:
  4055. {
  4056. m_value.string->clear();
  4057. break;
  4058. }
  4059. case value_t::binary:
  4060. {
  4061. m_value.binary->clear();
  4062. break;
  4063. }
  4064. case value_t::array:
  4065. {
  4066. m_value.array->clear();
  4067. break;
  4068. }
  4069. case value_t::object:
  4070. {
  4071. m_value.object->clear();
  4072. break;
  4073. }
  4074. default:
  4075. break;
  4076. }
  4077. }
  4078. /*!
  4079. @brief add an object to an array
  4080. Appends the given element @a val to the end of the JSON value. If the
  4081. function is called on a JSON null value, an empty array is created before
  4082. appending @a val.
  4083. @param[in] val the value to add to the JSON array
  4084. @throw type_error.308 when called on a type other than JSON array or
  4085. null; example: `"cannot use push_back() with number"`
  4086. @complexity Amortized constant.
  4087. @liveexample{The example shows how `push_back()` and `+=` can be used to
  4088. add elements to a JSON array. Note how the `null` value was silently
  4089. converted to a JSON array.,push_back}
  4090. @since version 1.0.0
  4091. */
  4092. void push_back(basic_json&& val)
  4093. {
  4094. // push_back only works for null objects or arrays
  4095. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
  4096. {
  4097. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  4098. }
  4099. // transform null object into an array
  4100. if (is_null())
  4101. {
  4102. m_type = value_t::array;
  4103. m_value = value_t::array;
  4104. assert_invariant();
  4105. }
  4106. // add element to array (move semantics)
  4107. m_value.array->push_back(std::move(val));
  4108. // if val is moved from, basic_json move constructor marks it null so we do not call the destructor
  4109. }
  4110. /*!
  4111. @brief add an object to an array
  4112. @copydoc push_back(basic_json&&)
  4113. */
  4114. reference operator+=(basic_json&& val)
  4115. {
  4116. push_back(std::move(val));
  4117. return *this;
  4118. }
  4119. /*!
  4120. @brief add an object to an array
  4121. @copydoc push_back(basic_json&&)
  4122. */
  4123. void push_back(const basic_json& val)
  4124. {
  4125. // push_back only works for null objects or arrays
  4126. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
  4127. {
  4128. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  4129. }
  4130. // transform null object into an array
  4131. if (is_null())
  4132. {
  4133. m_type = value_t::array;
  4134. m_value = value_t::array;
  4135. assert_invariant();
  4136. }
  4137. // add element to array
  4138. m_value.array->push_back(val);
  4139. }
  4140. /*!
  4141. @brief add an object to an array
  4142. @copydoc push_back(basic_json&&)
  4143. */
  4144. reference operator+=(const basic_json& val)
  4145. {
  4146. push_back(val);
  4147. return *this;
  4148. }
  4149. /*!
  4150. @brief add an object to an object
  4151. Inserts the given element @a val to the JSON object. If the function is
  4152. called on a JSON null value, an empty object is created before inserting
  4153. @a val.
  4154. @param[in] val the value to add to the JSON object
  4155. @throw type_error.308 when called on a type other than JSON object or
  4156. null; example: `"cannot use push_back() with number"`
  4157. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  4158. @liveexample{The example shows how `push_back()` and `+=` can be used to
  4159. add elements to a JSON object. Note how the `null` value was silently
  4160. converted to a JSON object.,push_back__object_t__value}
  4161. @since version 1.0.0
  4162. */
  4163. void push_back(const typename object_t::value_type& val)
  4164. {
  4165. // push_back only works for null objects or objects
  4166. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_object())))
  4167. {
  4168. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  4169. }
  4170. // transform null object into an object
  4171. if (is_null())
  4172. {
  4173. m_type = value_t::object;
  4174. m_value = value_t::object;
  4175. assert_invariant();
  4176. }
  4177. // add element to array
  4178. m_value.object->insert(val);
  4179. }
  4180. /*!
  4181. @brief add an object to an object
  4182. @copydoc push_back(const typename object_t::value_type&)
  4183. */
  4184. reference operator+=(const typename object_t::value_type& val)
  4185. {
  4186. push_back(val);
  4187. return *this;
  4188. }
  4189. /*!
  4190. @brief add an object to an object
  4191. This function allows to use `push_back` with an initializer list. In case
  4192. 1. the current value is an object,
  4193. 2. the initializer list @a init contains only two elements, and
  4194. 3. the first element of @a init is a string,
  4195. @a init is converted into an object element and added using
  4196. @ref push_back(const typename object_t::value_type&). Otherwise, @a init
  4197. is converted to a JSON value and added using @ref push_back(basic_json&&).
  4198. @param[in] init an initializer list
  4199. @complexity Linear in the size of the initializer list @a init.
  4200. @note This function is required to resolve an ambiguous overload error,
  4201. because pairs like `{"key", "value"}` can be both interpreted as
  4202. `object_t::value_type` or `std::initializer_list<basic_json>`, see
  4203. https://github.com/nlohmann/json/issues/235 for more information.
  4204. @liveexample{The example shows how initializer lists are treated as
  4205. objects when possible.,push_back__initializer_list}
  4206. */
  4207. void push_back(initializer_list_t init)
  4208. {
  4209. if (is_object() and init.size() == 2 and (*init.begin())->is_string())
  4210. {
  4211. basic_json&& key = init.begin()->moved_or_copied();
  4212. push_back(typename object_t::value_type(
  4213. std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
  4214. }
  4215. else
  4216. {
  4217. push_back(basic_json(init));
  4218. }
  4219. }
  4220. /*!
  4221. @brief add an object to an object
  4222. @copydoc push_back(initializer_list_t)
  4223. */
  4224. reference operator+=(initializer_list_t init)
  4225. {
  4226. push_back(init);
  4227. return *this;
  4228. }
  4229. /*!
  4230. @brief add an object to an array
  4231. Creates a JSON value from the passed parameters @a args to the end of the
  4232. JSON value. If the function is called on a JSON null value, an empty array
  4233. is created before appending the value created from @a args.
  4234. @param[in] args arguments to forward to a constructor of @ref basic_json
  4235. @tparam Args compatible types to create a @ref basic_json object
  4236. @return reference to the inserted element
  4237. @throw type_error.311 when called on a type other than JSON array or
  4238. null; example: `"cannot use emplace_back() with number"`
  4239. @complexity Amortized constant.
  4240. @liveexample{The example shows how `push_back()` can be used to add
  4241. elements to a JSON array. Note how the `null` value was silently converted
  4242. to a JSON array.,emplace_back}
  4243. @since version 2.0.8, returns reference since 3.7.0
  4244. */
  4245. template<class... Args>
  4246. reference emplace_back(Args&& ... args)
  4247. {
  4248. // emplace_back only works for null objects or arrays
  4249. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
  4250. {
  4251. JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name())));
  4252. }
  4253. // transform null object into an array
  4254. if (is_null())
  4255. {
  4256. m_type = value_t::array;
  4257. m_value = value_t::array;
  4258. assert_invariant();
  4259. }
  4260. // add element to array (perfect forwarding)
  4261. #ifdef JSON_HAS_CPP_17
  4262. return m_value.array->emplace_back(std::forward<Args>(args)...);
  4263. #else
  4264. m_value.array->emplace_back(std::forward<Args>(args)...);
  4265. return m_value.array->back();
  4266. #endif
  4267. }
  4268. /*!
  4269. @brief add an object to an object if key does not exist
  4270. Inserts a new element into a JSON object constructed in-place with the
  4271. given @a args if there is no element with the key in the container. If the
  4272. function is called on a JSON null value, an empty object is created before
  4273. appending the value created from @a args.
  4274. @param[in] args arguments to forward to a constructor of @ref basic_json
  4275. @tparam Args compatible types to create a @ref basic_json object
  4276. @return a pair consisting of an iterator to the inserted element, or the
  4277. already-existing element if no insertion happened, and a bool
  4278. denoting whether the insertion took place.
  4279. @throw type_error.311 when called on a type other than JSON object or
  4280. null; example: `"cannot use emplace() with number"`
  4281. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  4282. @liveexample{The example shows how `emplace()` can be used to add elements
  4283. to a JSON object. Note how the `null` value was silently converted to a
  4284. JSON object. Further note how no value is added if there was already one
  4285. value stored with the same key.,emplace}
  4286. @since version 2.0.8
  4287. */
  4288. template<class... Args>
  4289. std::pair<iterator, bool> emplace(Args&& ... args)
  4290. {
  4291. // emplace only works for null objects or arrays
  4292. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_object())))
  4293. {
  4294. JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name())));
  4295. }
  4296. // transform null object into an object
  4297. if (is_null())
  4298. {
  4299. m_type = value_t::object;
  4300. m_value = value_t::object;
  4301. assert_invariant();
  4302. }
  4303. // add element to array (perfect forwarding)
  4304. auto res = m_value.object->emplace(std::forward<Args>(args)...);
  4305. // create result iterator and set iterator to the result of emplace
  4306. auto it = begin();
  4307. it.m_it.object_iterator = res.first;
  4308. // return pair of iterator and boolean
  4309. return {it, res.second};
  4310. }
  4311. /// Helper for insertion of an iterator
  4312. /// @note: This uses std::distance to support GCC 4.8,
  4313. /// see https://github.com/nlohmann/json/pull/1257
  4314. template<typename... Args>
  4315. iterator insert_iterator(const_iterator pos, Args&& ... args)
  4316. {
  4317. iterator result(this);
  4318. assert(m_value.array != nullptr);
  4319. auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator);
  4320. m_value.array->insert(pos.m_it.array_iterator, std::forward<Args>(args)...);
  4321. result.m_it.array_iterator = m_value.array->begin() + insert_pos;
  4322. // This could have been written as:
  4323. // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
  4324. // but the return value of insert is missing in GCC 4.8, so it is written this way instead.
  4325. return result;
  4326. }
  4327. /*!
  4328. @brief inserts element
  4329. Inserts element @a val before iterator @a pos.
  4330. @param[in] pos iterator before which the content will be inserted; may be
  4331. the end() iterator
  4332. @param[in] val element to insert
  4333. @return iterator pointing to the inserted @a val.
  4334. @throw type_error.309 if called on JSON values other than arrays;
  4335. example: `"cannot use insert() with string"`
  4336. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  4337. example: `"iterator does not fit current value"`
  4338. @complexity Constant plus linear in the distance between @a pos and end of
  4339. the container.
  4340. @liveexample{The example shows how `insert()` is used.,insert}
  4341. @since version 1.0.0
  4342. */
  4343. iterator insert(const_iterator pos, const basic_json& val)
  4344. {
  4345. // insert only works for arrays
  4346. if (JSON_HEDLEY_LIKELY(is_array()))
  4347. {
  4348. // check if iterator pos fits to this JSON value
  4349. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  4350. {
  4351. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  4352. }
  4353. // insert to array and return iterator
  4354. return insert_iterator(pos, val);
  4355. }
  4356. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  4357. }
  4358. /*!
  4359. @brief inserts element
  4360. @copydoc insert(const_iterator, const basic_json&)
  4361. */
  4362. iterator insert(const_iterator pos, basic_json&& val)
  4363. {
  4364. return insert(pos, val);
  4365. }
  4366. /*!
  4367. @brief inserts elements
  4368. Inserts @a cnt copies of @a val before iterator @a pos.
  4369. @param[in] pos iterator before which the content will be inserted; may be
  4370. the end() iterator
  4371. @param[in] cnt number of copies of @a val to insert
  4372. @param[in] val element to insert
  4373. @return iterator pointing to the first element inserted, or @a pos if
  4374. `cnt==0`
  4375. @throw type_error.309 if called on JSON values other than arrays; example:
  4376. `"cannot use insert() with string"`
  4377. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  4378. example: `"iterator does not fit current value"`
  4379. @complexity Linear in @a cnt plus linear in the distance between @a pos
  4380. and end of the container.
  4381. @liveexample{The example shows how `insert()` is used.,insert__count}
  4382. @since version 1.0.0
  4383. */
  4384. iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
  4385. {
  4386. // insert only works for arrays
  4387. if (JSON_HEDLEY_LIKELY(is_array()))
  4388. {
  4389. // check if iterator pos fits to this JSON value
  4390. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  4391. {
  4392. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  4393. }
  4394. // insert to array and return iterator
  4395. return insert_iterator(pos, cnt, val);
  4396. }
  4397. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  4398. }
  4399. /*!
  4400. @brief inserts elements
  4401. Inserts elements from range `[first, last)` before iterator @a pos.
  4402. @param[in] pos iterator before which the content will be inserted; may be
  4403. the end() iterator
  4404. @param[in] first begin of the range of elements to insert
  4405. @param[in] last end of the range of elements to insert
  4406. @throw type_error.309 if called on JSON values other than arrays; example:
  4407. `"cannot use insert() with string"`
  4408. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  4409. example: `"iterator does not fit current value"`
  4410. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  4411. same JSON value; example: `"iterators do not fit"`
  4412. @throw invalid_iterator.211 if @a first or @a last are iterators into
  4413. container for which insert is called; example: `"passed iterators may not
  4414. belong to container"`
  4415. @return iterator pointing to the first element inserted, or @a pos if
  4416. `first==last`
  4417. @complexity Linear in `std::distance(first, last)` plus linear in the
  4418. distance between @a pos and end of the container.
  4419. @liveexample{The example shows how `insert()` is used.,insert__range}
  4420. @since version 1.0.0
  4421. */
  4422. iterator insert(const_iterator pos, const_iterator first, const_iterator last)
  4423. {
  4424. // insert only works for arrays
  4425. if (JSON_HEDLEY_UNLIKELY(not is_array()))
  4426. {
  4427. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  4428. }
  4429. // check if iterator pos fits to this JSON value
  4430. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  4431. {
  4432. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  4433. }
  4434. // check if range iterators belong to the same JSON object
  4435. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  4436. {
  4437. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  4438. }
  4439. if (JSON_HEDLEY_UNLIKELY(first.m_object == this))
  4440. {
  4441. JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container"));
  4442. }
  4443. // insert to array and return iterator
  4444. return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator);
  4445. }
  4446. /*!
  4447. @brief inserts elements
  4448. Inserts elements from initializer list @a ilist before iterator @a pos.
  4449. @param[in] pos iterator before which the content will be inserted; may be
  4450. the end() iterator
  4451. @param[in] ilist initializer list to insert the values from
  4452. @throw type_error.309 if called on JSON values other than arrays; example:
  4453. `"cannot use insert() with string"`
  4454. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  4455. example: `"iterator does not fit current value"`
  4456. @return iterator pointing to the first element inserted, or @a pos if
  4457. `ilist` is empty
  4458. @complexity Linear in `ilist.size()` plus linear in the distance between
  4459. @a pos and end of the container.
  4460. @liveexample{The example shows how `insert()` is used.,insert__ilist}
  4461. @since version 1.0.0
  4462. */
  4463. iterator insert(const_iterator pos, initializer_list_t ilist)
  4464. {
  4465. // insert only works for arrays
  4466. if (JSON_HEDLEY_UNLIKELY(not is_array()))
  4467. {
  4468. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  4469. }
  4470. // check if iterator pos fits to this JSON value
  4471. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  4472. {
  4473. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  4474. }
  4475. // insert to array and return iterator
  4476. return insert_iterator(pos, ilist.begin(), ilist.end());
  4477. }
  4478. /*!
  4479. @brief inserts elements
  4480. Inserts elements from range `[first, last)`.
  4481. @param[in] first begin of the range of elements to insert
  4482. @param[in] last end of the range of elements to insert
  4483. @throw type_error.309 if called on JSON values other than objects; example:
  4484. `"cannot use insert() with string"`
  4485. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  4486. point to an object; example: `"iterators first and last must point to
  4487. objects"`
  4488. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  4489. same JSON value; example: `"iterators do not fit"`
  4490. @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
  4491. of elements to insert.
  4492. @liveexample{The example shows how `insert()` is used.,insert__range_object}
  4493. @since version 3.0.0
  4494. */
  4495. void insert(const_iterator first, const_iterator last)
  4496. {
  4497. // insert only works for objects
  4498. if (JSON_HEDLEY_UNLIKELY(not is_object()))
  4499. {
  4500. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  4501. }
  4502. // check if range iterators belong to the same JSON object
  4503. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  4504. {
  4505. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  4506. }
  4507. // passed iterators must belong to objects
  4508. if (JSON_HEDLEY_UNLIKELY(not first.m_object->is_object()))
  4509. {
  4510. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  4511. }
  4512. m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
  4513. }
  4514. /*!
  4515. @brief updates a JSON object from another object, overwriting existing keys
  4516. Inserts all values from JSON object @a j and overwrites existing keys.
  4517. @param[in] j JSON object to read values from
  4518. @throw type_error.312 if called on JSON values other than objects; example:
  4519. `"cannot use update() with string"`
  4520. @complexity O(N*log(size() + N)), where N is the number of elements to
  4521. insert.
  4522. @liveexample{The example shows how `update()` is used.,update}
  4523. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  4524. @since version 3.0.0
  4525. */
  4526. void update(const_reference j)
  4527. {
  4528. // implicitly convert null value to an empty object
  4529. if (is_null())
  4530. {
  4531. m_type = value_t::object;
  4532. m_value.object = create<object_t>();
  4533. assert_invariant();
  4534. }
  4535. if (JSON_HEDLEY_UNLIKELY(not is_object()))
  4536. {
  4537. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  4538. }
  4539. if (JSON_HEDLEY_UNLIKELY(not j.is_object()))
  4540. {
  4541. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name())));
  4542. }
  4543. for (auto it = j.cbegin(); it != j.cend(); ++it)
  4544. {
  4545. m_value.object->operator[](it.key()) = it.value();
  4546. }
  4547. }
  4548. /*!
  4549. @brief updates a JSON object from another object, overwriting existing keys
  4550. Inserts all values from from range `[first, last)` and overwrites existing
  4551. keys.
  4552. @param[in] first begin of the range of elements to insert
  4553. @param[in] last end of the range of elements to insert
  4554. @throw type_error.312 if called on JSON values other than objects; example:
  4555. `"cannot use update() with string"`
  4556. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  4557. point to an object; example: `"iterators first and last must point to
  4558. objects"`
  4559. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  4560. same JSON value; example: `"iterators do not fit"`
  4561. @complexity O(N*log(size() + N)), where N is the number of elements to
  4562. insert.
  4563. @liveexample{The example shows how `update()` is used__range.,update}
  4564. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  4565. @since version 3.0.0
  4566. */
  4567. void update(const_iterator first, const_iterator last)
  4568. {
  4569. // implicitly convert null value to an empty object
  4570. if (is_null())
  4571. {
  4572. m_type = value_t::object;
  4573. m_value.object = create<object_t>();
  4574. assert_invariant();
  4575. }
  4576. if (JSON_HEDLEY_UNLIKELY(not is_object()))
  4577. {
  4578. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  4579. }
  4580. // check if range iterators belong to the same JSON object
  4581. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  4582. {
  4583. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  4584. }
  4585. // passed iterators must belong to objects
  4586. if (JSON_HEDLEY_UNLIKELY(not first.m_object->is_object()
  4587. or not last.m_object->is_object()))
  4588. {
  4589. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  4590. }
  4591. for (auto it = first; it != last; ++it)
  4592. {
  4593. m_value.object->operator[](it.key()) = it.value();
  4594. }
  4595. }
  4596. /*!
  4597. @brief exchanges the values
  4598. Exchanges the contents of the JSON value with those of @a other. Does not
  4599. invoke any move, copy, or swap operations on individual elements. All
  4600. iterators and references remain valid. The past-the-end iterator is
  4601. invalidated.
  4602. @param[in,out] other JSON value to exchange the contents with
  4603. @complexity Constant.
  4604. @liveexample{The example below shows how JSON values can be swapped with
  4605. `swap()`.,swap__reference}
  4606. @since version 1.0.0
  4607. */
  4608. void swap(reference other) noexcept (
  4609. std::is_nothrow_move_constructible<value_t>::value and
  4610. std::is_nothrow_move_assignable<value_t>::value and
  4611. std::is_nothrow_move_constructible<json_value>::value and
  4612. std::is_nothrow_move_assignable<json_value>::value
  4613. )
  4614. {
  4615. std::swap(m_type, other.m_type);
  4616. std::swap(m_value, other.m_value);
  4617. assert_invariant();
  4618. }
  4619. /*!
  4620. @brief exchanges the values
  4621. Exchanges the contents of a JSON array with those of @a other. Does not
  4622. invoke any move, copy, or swap operations on individual elements. All
  4623. iterators and references remain valid. The past-the-end iterator is
  4624. invalidated.
  4625. @param[in,out] other array to exchange the contents with
  4626. @throw type_error.310 when JSON value is not an array; example: `"cannot
  4627. use swap() with string"`
  4628. @complexity Constant.
  4629. @liveexample{The example below shows how arrays can be swapped with
  4630. `swap()`.,swap__array_t}
  4631. @since version 1.0.0
  4632. */
  4633. void swap(array_t& other)
  4634. {
  4635. // swap only works for arrays
  4636. if (JSON_HEDLEY_LIKELY(is_array()))
  4637. {
  4638. std::swap(*(m_value.array), other);
  4639. }
  4640. else
  4641. {
  4642. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  4643. }
  4644. }
  4645. /*!
  4646. @brief exchanges the values
  4647. Exchanges the contents of a JSON object with those of @a other. Does not
  4648. invoke any move, copy, or swap operations on individual elements. All
  4649. iterators and references remain valid. The past-the-end iterator is
  4650. invalidated.
  4651. @param[in,out] other object to exchange the contents with
  4652. @throw type_error.310 when JSON value is not an object; example:
  4653. `"cannot use swap() with string"`
  4654. @complexity Constant.
  4655. @liveexample{The example below shows how objects can be swapped with
  4656. `swap()`.,swap__object_t}
  4657. @since version 1.0.0
  4658. */
  4659. void swap(object_t& other)
  4660. {
  4661. // swap only works for objects
  4662. if (JSON_HEDLEY_LIKELY(is_object()))
  4663. {
  4664. std::swap(*(m_value.object), other);
  4665. }
  4666. else
  4667. {
  4668. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  4669. }
  4670. }
  4671. /*!
  4672. @brief exchanges the values
  4673. Exchanges the contents of a JSON string with those of @a other. Does not
  4674. invoke any move, copy, or swap operations on individual elements. All
  4675. iterators and references remain valid. The past-the-end iterator is
  4676. invalidated.
  4677. @param[in,out] other string to exchange the contents with
  4678. @throw type_error.310 when JSON value is not a string; example: `"cannot
  4679. use swap() with boolean"`
  4680. @complexity Constant.
  4681. @liveexample{The example below shows how strings can be swapped with
  4682. `swap()`.,swap__string_t}
  4683. @since version 1.0.0
  4684. */
  4685. void swap(string_t& other)
  4686. {
  4687. // swap only works for strings
  4688. if (JSON_HEDLEY_LIKELY(is_string()))
  4689. {
  4690. std::swap(*(m_value.string), other);
  4691. }
  4692. else
  4693. {
  4694. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  4695. }
  4696. }
  4697. /*!
  4698. @brief exchanges the values
  4699. Exchanges the contents of a JSON string with those of @a other. Does not
  4700. invoke any move, copy, or swap operations on individual elements. All
  4701. iterators and references remain valid. The past-the-end iterator is
  4702. invalidated.
  4703. @param[in,out] other binary to exchange the contents with
  4704. @throw type_error.310 when JSON value is not a string; example: `"cannot
  4705. use swap() with boolean"`
  4706. @complexity Constant.
  4707. @liveexample{The example below shows how strings can be swapped with
  4708. `swap()`.,swap__binary_t}
  4709. @since version 3.8.0
  4710. */
  4711. void swap(binary_t& other)
  4712. {
  4713. // swap only works for strings
  4714. if (JSON_HEDLEY_LIKELY(is_binary()))
  4715. {
  4716. std::swap(*(m_value.binary), other);
  4717. }
  4718. else
  4719. {
  4720. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  4721. }
  4722. }
  4723. /// @copydoc swap(binary_t)
  4724. void swap(typename binary_t::container_type& other)
  4725. {
  4726. // swap only works for strings
  4727. if (JSON_HEDLEY_LIKELY(is_binary()))
  4728. {
  4729. std::swap(*(m_value.binary), other);
  4730. }
  4731. else
  4732. {
  4733. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  4734. }
  4735. }
  4736. /// @}
  4737. public:
  4738. //////////////////////////////////////////
  4739. // lexicographical comparison operators //
  4740. //////////////////////////////////////////
  4741. /// @name lexicographical comparison operators
  4742. /// @{
  4743. /*!
  4744. @brief comparison: equal
  4745. Compares two JSON values for equality according to the following rules:
  4746. - Two JSON values are equal if (1) they are from the same type and (2)
  4747. their stored values are the same according to their respective
  4748. `operator==`.
  4749. - Integer and floating-point numbers are automatically converted before
  4750. comparison. Note that two NaN values are always treated as unequal.
  4751. - Two JSON null values are equal.
  4752. @note Floating-point inside JSON values numbers are compared with
  4753. `json::number_float_t::operator==` which is `double::operator==` by
  4754. default. To compare floating-point while respecting an epsilon, an alternative
  4755. [comparison function](https://github.com/mariokonrad/marnav/blob/master/include/marnav/math/floatingpoint.hpp#L34-#L39)
  4756. could be used, for instance
  4757. @code {.cpp}
  4758. template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
  4759. inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
  4760. {
  4761. return std::abs(a - b) <= epsilon;
  4762. }
  4763. @endcode
  4764. Or you can self-defined operator equal function like this:
  4765. @code {.cpp}
  4766. bool my_equal(const_reference lhs, const_reference rhs) {
  4767. const auto lhs_type lhs.type();
  4768. const auto rhs_type rhs.type();
  4769. if (lhs_type == rhs_type) {
  4770. switch(lhs_type)
  4771. // self_defined case
  4772. case value_t::number_float:
  4773. return std::abs(lhs - rhs) <= std::numeric_limits<float>::epsilon();
  4774. // other cases remain the same with the original
  4775. ...
  4776. }
  4777. ...
  4778. }
  4779. @endcode
  4780. @note NaN values never compare equal to themselves or to other NaN values.
  4781. @param[in] lhs first JSON value to consider
  4782. @param[in] rhs second JSON value to consider
  4783. @return whether the values @a lhs and @a rhs are equal
  4784. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  4785. @complexity Linear.
  4786. @liveexample{The example demonstrates comparing several JSON
  4787. types.,operator__equal}
  4788. @since version 1.0.0
  4789. */
  4790. friend bool operator==(const_reference lhs, const_reference rhs) noexcept
  4791. {
  4792. const auto lhs_type = lhs.type();
  4793. const auto rhs_type = rhs.type();
  4794. if (lhs_type == rhs_type)
  4795. {
  4796. switch (lhs_type)
  4797. {
  4798. case value_t::array:
  4799. return *lhs.m_value.array == *rhs.m_value.array;
  4800. case value_t::object:
  4801. return *lhs.m_value.object == *rhs.m_value.object;
  4802. case value_t::null:
  4803. return true;
  4804. case value_t::string:
  4805. return *lhs.m_value.string == *rhs.m_value.string;
  4806. case value_t::boolean:
  4807. return lhs.m_value.boolean == rhs.m_value.boolean;
  4808. case value_t::number_integer:
  4809. return lhs.m_value.number_integer == rhs.m_value.number_integer;
  4810. case value_t::number_unsigned:
  4811. return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned;
  4812. case value_t::number_float:
  4813. return lhs.m_value.number_float == rhs.m_value.number_float;
  4814. case value_t::binary:
  4815. return *lhs.m_value.binary == *rhs.m_value.binary;
  4816. default:
  4817. return false;
  4818. }
  4819. }
  4820. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  4821. {
  4822. return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float;
  4823. }
  4824. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  4825. {
  4826. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer);
  4827. }
  4828. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  4829. {
  4830. return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float;
  4831. }
  4832. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  4833. {
  4834. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned);
  4835. }
  4836. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  4837. {
  4838. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer;
  4839. }
  4840. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  4841. {
  4842. return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  4843. }
  4844. return false;
  4845. }
  4846. /*!
  4847. @brief comparison: equal
  4848. @copydoc operator==(const_reference, const_reference)
  4849. */
  4850. template<typename ScalarType, typename std::enable_if<
  4851. std::is_scalar<ScalarType>::value, int>::type = 0>
  4852. friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept
  4853. {
  4854. return lhs == basic_json(rhs);
  4855. }
  4856. /*!
  4857. @brief comparison: equal
  4858. @copydoc operator==(const_reference, const_reference)
  4859. */
  4860. template<typename ScalarType, typename std::enable_if<
  4861. std::is_scalar<ScalarType>::value, int>::type = 0>
  4862. friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept
  4863. {
  4864. return basic_json(lhs) == rhs;
  4865. }
  4866. /*!
  4867. @brief comparison: not equal
  4868. Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
  4869. @param[in] lhs first JSON value to consider
  4870. @param[in] rhs second JSON value to consider
  4871. @return whether the values @a lhs and @a rhs are not equal
  4872. @complexity Linear.
  4873. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  4874. @liveexample{The example demonstrates comparing several JSON
  4875. types.,operator__notequal}
  4876. @since version 1.0.0
  4877. */
  4878. friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
  4879. {
  4880. return not (lhs == rhs);
  4881. }
  4882. /*!
  4883. @brief comparison: not equal
  4884. @copydoc operator!=(const_reference, const_reference)
  4885. */
  4886. template<typename ScalarType, typename std::enable_if<
  4887. std::is_scalar<ScalarType>::value, int>::type = 0>
  4888. friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept
  4889. {
  4890. return lhs != basic_json(rhs);
  4891. }
  4892. /*!
  4893. @brief comparison: not equal
  4894. @copydoc operator!=(const_reference, const_reference)
  4895. */
  4896. template<typename ScalarType, typename std::enable_if<
  4897. std::is_scalar<ScalarType>::value, int>::type = 0>
  4898. friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept
  4899. {
  4900. return basic_json(lhs) != rhs;
  4901. }
  4902. /*!
  4903. @brief comparison: less than
  4904. Compares whether one JSON value @a lhs is less than another JSON value @a
  4905. rhs according to the following rules:
  4906. - If @a lhs and @a rhs have the same type, the values are compared using
  4907. the default `<` operator.
  4908. - Integer and floating-point numbers are automatically converted before
  4909. comparison
  4910. - In case @a lhs and @a rhs have different types, the values are ignored
  4911. and the order of the types is considered, see
  4912. @ref operator<(const value_t, const value_t).
  4913. @param[in] lhs first JSON value to consider
  4914. @param[in] rhs second JSON value to consider
  4915. @return whether @a lhs is less than @a rhs
  4916. @complexity Linear.
  4917. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  4918. @liveexample{The example demonstrates comparing several JSON
  4919. types.,operator__less}
  4920. @since version 1.0.0
  4921. */
  4922. friend bool operator<(const_reference lhs, const_reference rhs) noexcept
  4923. {
  4924. const auto lhs_type = lhs.type();
  4925. const auto rhs_type = rhs.type();
  4926. if (lhs_type == rhs_type)
  4927. {
  4928. switch (lhs_type)
  4929. {
  4930. case value_t::array:
  4931. // note parentheses are necessary, see
  4932. // https://github.com/nlohmann/json/issues/1530
  4933. return (*lhs.m_value.array) < (*rhs.m_value.array);
  4934. case value_t::object:
  4935. return (*lhs.m_value.object) < (*rhs.m_value.object);
  4936. case value_t::null:
  4937. return false;
  4938. case value_t::string:
  4939. return (*lhs.m_value.string) < (*rhs.m_value.string);
  4940. case value_t::boolean:
  4941. return (lhs.m_value.boolean) < (rhs.m_value.boolean);
  4942. case value_t::number_integer:
  4943. return (lhs.m_value.number_integer) < (rhs.m_value.number_integer);
  4944. case value_t::number_unsigned:
  4945. return (lhs.m_value.number_unsigned) < (rhs.m_value.number_unsigned);
  4946. case value_t::number_float:
  4947. return (lhs.m_value.number_float) < (rhs.m_value.number_float);
  4948. case value_t::binary:
  4949. return (*lhs.m_value.binary) < (*rhs.m_value.binary);
  4950. default:
  4951. return false;
  4952. }
  4953. }
  4954. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  4955. {
  4956. return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
  4957. }
  4958. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  4959. {
  4960. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
  4961. }
  4962. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  4963. {
  4964. return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
  4965. }
  4966. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  4967. {
  4968. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
  4969. }
  4970. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  4971. {
  4972. return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  4973. }
  4974. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  4975. {
  4976. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
  4977. }
  4978. // We only reach this line if we cannot compare values. In that case,
  4979. // we compare types. Note we have to call the operator explicitly,
  4980. // because MSVC has problems otherwise.
  4981. return operator<(lhs_type, rhs_type);
  4982. }
  4983. /*!
  4984. @brief comparison: less than
  4985. @copydoc operator<(const_reference, const_reference)
  4986. */
  4987. template<typename ScalarType, typename std::enable_if<
  4988. std::is_scalar<ScalarType>::value, int>::type = 0>
  4989. friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept
  4990. {
  4991. return lhs < basic_json(rhs);
  4992. }
  4993. /*!
  4994. @brief comparison: less than
  4995. @copydoc operator<(const_reference, const_reference)
  4996. */
  4997. template<typename ScalarType, typename std::enable_if<
  4998. std::is_scalar<ScalarType>::value, int>::type = 0>
  4999. friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept
  5000. {
  5001. return basic_json(lhs) < rhs;
  5002. }
  5003. /*!
  5004. @brief comparison: less than or equal
  5005. Compares whether one JSON value @a lhs is less than or equal to another
  5006. JSON value by calculating `not (rhs < lhs)`.
  5007. @param[in] lhs first JSON value to consider
  5008. @param[in] rhs second JSON value to consider
  5009. @return whether @a lhs is less than or equal to @a rhs
  5010. @complexity Linear.
  5011. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  5012. @liveexample{The example demonstrates comparing several JSON
  5013. types.,operator__greater}
  5014. @since version 1.0.0
  5015. */
  5016. friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
  5017. {
  5018. return not (rhs < lhs);
  5019. }
  5020. /*!
  5021. @brief comparison: less than or equal
  5022. @copydoc operator<=(const_reference, const_reference)
  5023. */
  5024. template<typename ScalarType, typename std::enable_if<
  5025. std::is_scalar<ScalarType>::value, int>::type = 0>
  5026. friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept
  5027. {
  5028. return lhs <= basic_json(rhs);
  5029. }
  5030. /*!
  5031. @brief comparison: less than or equal
  5032. @copydoc operator<=(const_reference, const_reference)
  5033. */
  5034. template<typename ScalarType, typename std::enable_if<
  5035. std::is_scalar<ScalarType>::value, int>::type = 0>
  5036. friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept
  5037. {
  5038. return basic_json(lhs) <= rhs;
  5039. }
  5040. /*!
  5041. @brief comparison: greater than
  5042. Compares whether one JSON value @a lhs is greater than another
  5043. JSON value by calculating `not (lhs <= rhs)`.
  5044. @param[in] lhs first JSON value to consider
  5045. @param[in] rhs second JSON value to consider
  5046. @return whether @a lhs is greater than to @a rhs
  5047. @complexity Linear.
  5048. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  5049. @liveexample{The example demonstrates comparing several JSON
  5050. types.,operator__lessequal}
  5051. @since version 1.0.0
  5052. */
  5053. friend bool operator>(const_reference lhs, const_reference rhs) noexcept
  5054. {
  5055. return not (lhs <= rhs);
  5056. }
  5057. /*!
  5058. @brief comparison: greater than
  5059. @copydoc operator>(const_reference, const_reference)
  5060. */
  5061. template<typename ScalarType, typename std::enable_if<
  5062. std::is_scalar<ScalarType>::value, int>::type = 0>
  5063. friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept
  5064. {
  5065. return lhs > basic_json(rhs);
  5066. }
  5067. /*!
  5068. @brief comparison: greater than
  5069. @copydoc operator>(const_reference, const_reference)
  5070. */
  5071. template<typename ScalarType, typename std::enable_if<
  5072. std::is_scalar<ScalarType>::value, int>::type = 0>
  5073. friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept
  5074. {
  5075. return basic_json(lhs) > rhs;
  5076. }
  5077. /*!
  5078. @brief comparison: greater than or equal
  5079. Compares whether one JSON value @a lhs is greater than or equal to another
  5080. JSON value by calculating `not (lhs < rhs)`.
  5081. @param[in] lhs first JSON value to consider
  5082. @param[in] rhs second JSON value to consider
  5083. @return whether @a lhs is greater than or equal to @a rhs
  5084. @complexity Linear.
  5085. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  5086. @liveexample{The example demonstrates comparing several JSON
  5087. types.,operator__greaterequal}
  5088. @since version 1.0.0
  5089. */
  5090. friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
  5091. {
  5092. return not (lhs < rhs);
  5093. }
  5094. /*!
  5095. @brief comparison: greater than or equal
  5096. @copydoc operator>=(const_reference, const_reference)
  5097. */
  5098. template<typename ScalarType, typename std::enable_if<
  5099. std::is_scalar<ScalarType>::value, int>::type = 0>
  5100. friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept
  5101. {
  5102. return lhs >= basic_json(rhs);
  5103. }
  5104. /*!
  5105. @brief comparison: greater than or equal
  5106. @copydoc operator>=(const_reference, const_reference)
  5107. */
  5108. template<typename ScalarType, typename std::enable_if<
  5109. std::is_scalar<ScalarType>::value, int>::type = 0>
  5110. friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept
  5111. {
  5112. return basic_json(lhs) >= rhs;
  5113. }
  5114. /// @}
  5115. ///////////////////
  5116. // serialization //
  5117. ///////////////////
  5118. /// @name serialization
  5119. /// @{
  5120. /*!
  5121. @brief serialize to stream
  5122. Serialize the given JSON value @a j to the output stream @a o. The JSON
  5123. value will be serialized using the @ref dump member function.
  5124. - The indentation of the output can be controlled with the member variable
  5125. `width` of the output stream @a o. For instance, using the manipulator
  5126. `std::setw(4)` on @a o sets the indentation level to `4` and the
  5127. serialization result is the same as calling `dump(4)`.
  5128. - The indentation character can be controlled with the member variable
  5129. `fill` of the output stream @a o. For instance, the manipulator
  5130. `std::setfill('\\t')` sets indentation to use a tab character rather than
  5131. the default space character.
  5132. @param[in,out] o stream to serialize to
  5133. @param[in] j JSON value to serialize
  5134. @return the stream @a o
  5135. @throw type_error.316 if a string stored inside the JSON value is not
  5136. UTF-8 encoded
  5137. @complexity Linear.
  5138. @liveexample{The example below shows the serialization with different
  5139. parameters to `width` to adjust the indentation level.,operator_serialize}
  5140. @since version 1.0.0; indentation character added in version 3.0.0
  5141. */
  5142. friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
  5143. {
  5144. // read width member and use it as indentation parameter if nonzero
  5145. const bool pretty_print = o.width() > 0;
  5146. const auto indentation = pretty_print ? o.width() : 0;
  5147. // reset width to 0 for subsequent calls to this stream
  5148. o.width(0);
  5149. // do the actual serialization
  5150. serializer s(detail::output_adapter<char>(o), o.fill());
  5151. s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
  5152. return o;
  5153. }
  5154. /*!
  5155. @brief serialize to stream
  5156. @deprecated This stream operator is deprecated and will be removed in
  5157. future 4.0.0 of the library. Please use
  5158. @ref operator<<(std::ostream&, const basic_json&)
  5159. instead; that is, replace calls like `j >> o;` with `o << j;`.
  5160. @since version 1.0.0; deprecated since version 3.0.0
  5161. */
  5162. JSON_HEDLEY_DEPRECATED(3.0.0)
  5163. friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
  5164. {
  5165. return o << j;
  5166. }
  5167. /// @}
  5168. /////////////////////
  5169. // deserialization //
  5170. /////////////////////
  5171. /// @name deserialization
  5172. /// @{
  5173. /*!
  5174. @brief deserialize from a compatible input
  5175. This function reads from a compatible input. Examples are:
  5176. - an array of 1-byte values
  5177. - strings with character/literal type with size of 1 byte
  5178. - input streams
  5179. - container with contiguous storage of 1-byte values. Compatible container
  5180. types include `std::vector`, `std::string`, `std::array`,
  5181. `std::valarray`, and `std::initializer_list`. Furthermore, C-style
  5182. arrays can be used with `std::begin()`/`std::end()`. User-defined
  5183. containers can be used as long as they implement random-access iterators
  5184. and a contiguous storage.
  5185. @pre Each element of the container has a size of 1 byte. Violating this
  5186. precondition yields undefined behavior. **This precondition is enforced
  5187. with a static assertion.**
  5188. @pre The container storage is contiguous. Violating this precondition
  5189. yields undefined behavior. **This precondition is enforced with an
  5190. assertion.**
  5191. @warning There is no way to enforce all preconditions at compile-time. If
  5192. the function is called with a noncompliant container and with
  5193. assertions switched off, the behavior is undefined and will most
  5194. likely yield segmentation violation.
  5195. @param[in] i input to read from
  5196. @param[in] cb a parser callback function of type @ref parser_callback_t
  5197. which is used to control the deserialization by filtering unwanted values
  5198. (optional)
  5199. @param[in] allow_exceptions whether to throw exceptions in case of a
  5200. parse error (optional, true by default)
  5201. @return deserialized JSON value; in case of a parse error and
  5202. @a allow_exceptions set to `false`, the return value will be
  5203. value_t::discarded.
  5204. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  5205. of input; expected string literal""`
  5206. @throw parse_error.102 if to_unicode fails or surrogate error
  5207. @throw parse_error.103 if to_unicode fails
  5208. @complexity Linear in the length of the input. The parser is a predictive
  5209. LL(1) parser. The complexity can be higher if the parser callback function
  5210. @a cb has a super-linear complexity.
  5211. @note A UTF-8 byte order mark is silently ignored.
  5212. @liveexample{The example below demonstrates the `parse()` function reading
  5213. from an array.,parse__array__parser_callback_t}
  5214. @liveexample{The example below demonstrates the `parse()` function with
  5215. and without callback function.,parse__string__parser_callback_t}
  5216. @liveexample{The example below demonstrates the `parse()` function with
  5217. and without callback function.,parse__istream__parser_callback_t}
  5218. @liveexample{The example below demonstrates the `parse()` function reading
  5219. from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
  5220. @since version 2.0.3 (contiguous containers)
  5221. */
  5222. template<typename InputType>
  5223. JSON_HEDLEY_WARN_UNUSED_RESULT
  5224. static basic_json parse(InputType&& i,
  5225. const parser_callback_t cb = nullptr,
  5226. const bool allow_exceptions = true)
  5227. {
  5228. basic_json result;
  5229. parser(detail::input_adapter(std::forward<InputType>(i)), cb, allow_exceptions).parse(true, result);
  5230. return result;
  5231. }
  5232. JSON_HEDLEY_WARN_UNUSED_RESULT
  5233. static basic_json parse(detail::span_input_adapter&& i,
  5234. const parser_callback_t cb = nullptr,
  5235. const bool allow_exceptions = true)
  5236. {
  5237. basic_json result;
  5238. parser(i.get(), cb, allow_exceptions).parse(true, result);
  5239. return result;
  5240. }
  5241. template<typename InputType>
  5242. static bool accept(InputType&& i)
  5243. {
  5244. return parser(detail::input_adapter(std::forward<InputType>(i))).accept(true);
  5245. }
  5246. static bool accept(detail::span_input_adapter&& i)
  5247. {
  5248. return parser(i.get()).accept(true);
  5249. }
  5250. /*!
  5251. @brief generate SAX events
  5252. The SAX event lister must follow the interface of @ref json_sax.
  5253. This function reads from a compatible input. Examples are:
  5254. - an array of 1-byte values
  5255. - strings with character/literal type with size of 1 byte
  5256. - input streams
  5257. - container with contiguous storage of 1-byte values. Compatible container
  5258. types include `std::vector`, `std::string`, `std::array`,
  5259. `std::valarray`, and `std::initializer_list`. Furthermore, C-style
  5260. arrays can be used with `std::begin()`/`std::end()`. User-defined
  5261. containers can be used as long as they implement random-access iterators
  5262. and a contiguous storage.
  5263. @pre Each element of the container has a size of 1 byte. Violating this
  5264. precondition yields undefined behavior. **This precondition is enforced
  5265. with a static assertion.**
  5266. @pre The container storage is contiguous. Violating this precondition
  5267. yields undefined behavior. **This precondition is enforced with an
  5268. assertion.**
  5269. @warning There is no way to enforce all preconditions at compile-time. If
  5270. the function is called with a noncompliant container and with
  5271. assertions switched off, the behavior is undefined and will most
  5272. likely yield segmentation violation.
  5273. @param[in] i input to read from
  5274. @param[in,out] sax SAX event listener
  5275. @param[in] format the format to parse (JSON, CBOR, MessagePack, or UBJSON)
  5276. @param[in] strict whether the input has to be consumed completely
  5277. @return return value of the last processed SAX event
  5278. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  5279. of input; expected string literal""`
  5280. @throw parse_error.102 if to_unicode fails or surrogate error
  5281. @throw parse_error.103 if to_unicode fails
  5282. @complexity Linear in the length of the input. The parser is a predictive
  5283. LL(1) parser. The complexity can be higher if the SAX consumer @a sax has
  5284. a super-linear complexity.
  5285. @note A UTF-8 byte order mark is silently ignored.
  5286. @liveexample{The example below demonstrates the `sax_parse()` function
  5287. reading from string and processing the events with a user-defined SAX
  5288. event consumer.,sax_parse}
  5289. @since version 3.2.0
  5290. */
  5291. template <typename SAX, typename InputType>
  5292. JSON_HEDLEY_NON_NULL(2)
  5293. static bool sax_parse(InputType&& i, SAX* sax,
  5294. input_format_t format = input_format_t::json,
  5295. const bool strict = true)
  5296. {
  5297. auto ia = detail::input_adapter(std::forward<InputType>(i));
  5298. return format == input_format_t::json
  5299. ? parser(std::move(ia)).sax_parse(sax, strict)
  5300. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict);
  5301. }
  5302. template <typename SAX>
  5303. JSON_HEDLEY_NON_NULL(2)
  5304. static bool sax_parse(detail::span_input_adapter&& i, SAX* sax,
  5305. input_format_t format = input_format_t::json,
  5306. const bool strict = true)
  5307. {
  5308. auto ia = i.get();
  5309. return format == input_format_t::json
  5310. ? parser(std::move(ia)).sax_parse(sax, strict)
  5311. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict);
  5312. }
  5313. /*!
  5314. @brief deserialize from an iterator range with contiguous storage
  5315. This function reads from an iterator range of a container with contiguous
  5316. storage of 1-byte values. Compatible container types include
  5317. `std::vector`, `std::string`, `std::array`, `std::valarray`, and
  5318. `std::initializer_list`. Furthermore, C-style arrays can be used with
  5319. `std::begin()`/`std::end()`. User-defined containers can be used as long
  5320. as they implement random-access iterators and a contiguous storage.
  5321. @pre The iterator range is contiguous. Violating this precondition yields
  5322. undefined behavior. **This precondition is enforced with an assertion.**
  5323. @pre Each element in the range has a size of 1 byte. Violating this
  5324. precondition yields undefined behavior. **This precondition is enforced
  5325. with a static assertion.**
  5326. @warning There is no way to enforce all preconditions at compile-time. If
  5327. the function is called with noncompliant iterators and with
  5328. assertions switched off, the behavior is undefined and will most
  5329. likely yield segmentation violation.
  5330. @tparam IteratorType iterator of container with contiguous storage
  5331. @param[in] first begin of the range to parse (included)
  5332. @param[in] last end of the range to parse (excluded)
  5333. @param[in] cb a parser callback function of type @ref parser_callback_t
  5334. which is used to control the deserialization by filtering unwanted values
  5335. (optional)
  5336. @param[in] allow_exceptions whether to throw exceptions in case of a
  5337. parse error (optional, true by default)
  5338. @return deserialized JSON value; in case of a parse error and
  5339. @a allow_exceptions set to `false`, the return value will be
  5340. value_t::discarded.
  5341. @throw parse_error.101 in case of an unexpected token
  5342. @throw parse_error.102 if to_unicode fails or surrogate error
  5343. @throw parse_error.103 if to_unicode fails
  5344. @complexity Linear in the length of the input. The parser is a predictive
  5345. LL(1) parser. The complexity can be higher if the parser callback function
  5346. @a cb has a super-linear complexity.
  5347. @note A UTF-8 byte order mark is silently ignored.
  5348. @liveexample{The example below demonstrates the `parse()` function reading
  5349. from an iterator range.,parse__iteratortype__parser_callback_t}
  5350. @since version 2.0.3
  5351. */
  5352. template<class IteratorType, typename std::enable_if<
  5353. std::is_base_of<
  5354. std::random_access_iterator_tag,
  5355. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  5356. static basic_json parse(IteratorType first, IteratorType last,
  5357. const parser_callback_t cb = nullptr,
  5358. const bool allow_exceptions = true)
  5359. {
  5360. basic_json result;
  5361. parser(detail::input_adapter(first, last), cb, allow_exceptions).parse(true, result);
  5362. return result;
  5363. }
  5364. template<class IteratorType, typename std::enable_if<
  5365. std::is_base_of<
  5366. std::random_access_iterator_tag,
  5367. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  5368. static bool accept(IteratorType first, IteratorType last)
  5369. {
  5370. return parser(detail::input_adapter(first, last)).accept(true);
  5371. }
  5372. template<class IteratorType, class SAX, typename std::enable_if<
  5373. std::is_base_of<
  5374. std::random_access_iterator_tag,
  5375. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  5376. JSON_HEDLEY_NON_NULL(3)
  5377. static bool sax_parse(IteratorType first, IteratorType last, SAX* sax)
  5378. {
  5379. return parser(detail::input_adapter(first, last)).sax_parse(sax);
  5380. }
  5381. /*!
  5382. @brief deserialize from stream
  5383. @deprecated This stream operator is deprecated and will be removed in
  5384. version 4.0.0 of the library. Please use
  5385. @ref operator>>(std::istream&, basic_json&)
  5386. instead; that is, replace calls like `j << i;` with `i >> j;`.
  5387. @since version 1.0.0; deprecated since version 3.0.0
  5388. */
  5389. JSON_HEDLEY_DEPRECATED(3.0.0)
  5390. friend std::istream& operator<<(basic_json& j, std::istream& i)
  5391. {
  5392. return operator>>(i, j);
  5393. }
  5394. /*!
  5395. @brief deserialize from stream
  5396. Deserializes an input stream to a JSON value.
  5397. @param[in,out] i input stream to read a serialized JSON value from
  5398. @param[in,out] j JSON value to write the deserialized input to
  5399. @throw parse_error.101 in case of an unexpected token
  5400. @throw parse_error.102 if to_unicode fails or surrogate error
  5401. @throw parse_error.103 if to_unicode fails
  5402. @complexity Linear in the length of the input. The parser is a predictive
  5403. LL(1) parser.
  5404. @note A UTF-8 byte order mark is silently ignored.
  5405. @liveexample{The example below shows how a JSON value is constructed by
  5406. reading a serialization from a stream.,operator_deserialize}
  5407. @sa parse(std::istream&, const parser_callback_t) for a variant with a
  5408. parser callback function to filter values while parsing
  5409. @since version 1.0.0
  5410. */
  5411. friend std::istream& operator>>(std::istream& i, basic_json& j)
  5412. {
  5413. parser(detail::input_adapter(i)).parse(false, j);
  5414. return i;
  5415. }
  5416. /// @}
  5417. ///////////////////////////
  5418. // convenience functions //
  5419. ///////////////////////////
  5420. /*!
  5421. @brief return the type as string
  5422. Returns the type name as string to be used in error messages - usually to
  5423. indicate that a function was called on a wrong JSON type.
  5424. @return a string representation of a the @a m_type member:
  5425. Value type | return value
  5426. ----------- | -------------
  5427. null | `"null"`
  5428. boolean | `"boolean"`
  5429. string | `"string"`
  5430. number | `"number"` (for all number types)
  5431. object | `"object"`
  5432. array | `"array"`
  5433. binary | `"binary"`
  5434. discarded | `"discarded"`
  5435. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  5436. @complexity Constant.
  5437. @liveexample{The following code exemplifies `type_name()` for all JSON
  5438. types.,type_name}
  5439. @sa @ref type() -- return the type of the JSON value
  5440. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  5441. @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept`
  5442. since 3.0.0
  5443. */
  5444. JSON_HEDLEY_RETURNS_NON_NULL
  5445. const char* type_name() const noexcept
  5446. {
  5447. {
  5448. switch (m_type)
  5449. {
  5450. case value_t::null:
  5451. return "null";
  5452. case value_t::object:
  5453. return "object";
  5454. case value_t::array:
  5455. return "array";
  5456. case value_t::string:
  5457. return "string";
  5458. case value_t::boolean:
  5459. return "boolean";
  5460. case value_t::binary:
  5461. return "binary";
  5462. case value_t::discarded:
  5463. return "discarded";
  5464. default:
  5465. return "number";
  5466. }
  5467. }
  5468. }
  5469. private:
  5470. //////////////////////
  5471. // member variables //
  5472. //////////////////////
  5473. /// the type of the current element
  5474. value_t m_type = value_t::null;
  5475. /// the value of the current element
  5476. json_value m_value = {};
  5477. //////////////////////////////////////////
  5478. // binary serialization/deserialization //
  5479. //////////////////////////////////////////
  5480. /// @name binary serialization/deserialization support
  5481. /// @{
  5482. public:
  5483. /*!
  5484. @brief create a CBOR serialization of a given JSON value
  5485. Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
  5486. Binary Object Representation) serialization format. CBOR is a binary
  5487. serialization format which aims to be more compact than JSON itself, yet
  5488. more efficient to parse.
  5489. The library uses the following mapping from JSON values types to
  5490. CBOR types according to the CBOR specification (RFC 7049):
  5491. JSON value type | value/range | CBOR type | first byte
  5492. --------------- | ------------------------------------------ | ---------------------------------- | ---------------
  5493. null | `null` | Null | 0xF6
  5494. boolean | `true` | True | 0xF5
  5495. boolean | `false` | False | 0xF4
  5496. number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B
  5497. number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A
  5498. number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39
  5499. number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38
  5500. number_integer | -24..-1 | Negative integer | 0x20..0x37
  5501. number_integer | 0..23 | Integer | 0x00..0x17
  5502. number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18
  5503. number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  5504. number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  5505. number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  5506. number_unsigned | 0..23 | Integer | 0x00..0x17
  5507. number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18
  5508. number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  5509. number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  5510. number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  5511. number_float | *any value representable by a float* | Single-Precision Float | 0xFA
  5512. number_float | *any value NOT representable by a float* | Double-Precision Float | 0xFB
  5513. string | *length*: 0..23 | UTF-8 string | 0x60..0x77
  5514. string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78
  5515. string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79
  5516. string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A
  5517. string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B
  5518. array | *size*: 0..23 | array | 0x80..0x97
  5519. array | *size*: 23..255 | array (1 byte follow) | 0x98
  5520. array | *size*: 256..65535 | array (2 bytes follow) | 0x99
  5521. array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A
  5522. array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B
  5523. object | *size*: 0..23 | map | 0xA0..0xB7
  5524. object | *size*: 23..255 | map (1 byte follow) | 0xB8
  5525. object | *size*: 256..65535 | map (2 bytes follow) | 0xB9
  5526. object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA
  5527. object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB
  5528. binary | *size*: 0..23 | byte string | 0x40..0x57
  5529. binary | *size*: 23..255 | byte string (1 byte follow) | 0x58
  5530. binary | *size*: 256..65535 | byte string (2 bytes follow) | 0x59
  5531. binary | *size*: 65536..4294967295 | byte string (4 bytes follow) | 0x5A
  5532. binary | *size*: 4294967296..18446744073709551615 | byte string (8 bytes follow) | 0x5B
  5533. @note The mapping is **complete** in the sense that any JSON value type
  5534. can be converted to a CBOR value.
  5535. @note If NaN or Infinity are stored inside a JSON number, they are
  5536. serialized properly. This behavior differs from the @ref dump()
  5537. function which serializes NaN or Infinity to `null`.
  5538. @note The following CBOR types are not used in the conversion:
  5539. - UTF-8 strings terminated by "break" (0x7F)
  5540. - arrays terminated by "break" (0x9F)
  5541. - maps terminated by "break" (0xBF)
  5542. - byte strings terminated by "break" (0x5F)
  5543. - date/time (0xC0..0xC1)
  5544. - bignum (0xC2..0xC3)
  5545. - decimal fraction (0xC4)
  5546. - bigfloat (0xC5)
  5547. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  5548. - expected conversions (0xD5..0xD7)
  5549. - simple values (0xE0..0xF3, 0xF8)
  5550. - undefined (0xF7)
  5551. - half-precision floats (0xF9)
  5552. - break (0xFF)
  5553. @param[in] j JSON value to serialize
  5554. @return CBOR serialization as byte vector
  5555. @complexity Linear in the size of the JSON value @a j.
  5556. @liveexample{The example shows the serialization of a JSON value to a byte
  5557. vector in CBOR format.,to_cbor}
  5558. @sa http://cbor.io
  5559. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  5560. analogous deserialization
  5561. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  5562. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  5563. related UBJSON format
  5564. @since version 2.0.9; compact representation of floating-point numbers
  5565. since version 3.8.0
  5566. */
  5567. static std::vector<uint8_t> to_cbor(const basic_json& j)
  5568. {
  5569. std::vector<uint8_t> result;
  5570. to_cbor(j, result);
  5571. return result;
  5572. }
  5573. static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o)
  5574. {
  5575. binary_writer<uint8_t>(o).write_cbor(j);
  5576. }
  5577. static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
  5578. {
  5579. binary_writer<char>(o).write_cbor(j);
  5580. }
  5581. /*!
  5582. @brief create a MessagePack serialization of a given JSON value
  5583. Serializes a given JSON value @a j to a byte vector using the MessagePack
  5584. serialization format. MessagePack is a binary serialization format which
  5585. aims to be more compact than JSON itself, yet more efficient to parse.
  5586. The library uses the following mapping from JSON values types to
  5587. MessagePack types according to the MessagePack specification:
  5588. JSON value type | value/range | MessagePack type | first byte
  5589. --------------- | --------------------------------- | ---------------- | ----------
  5590. null | `null` | nil | 0xC0
  5591. boolean | `true` | true | 0xC3
  5592. boolean | `false` | false | 0xC2
  5593. number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3
  5594. number_integer | -2147483648..-32769 | int32 | 0xD2
  5595. number_integer | -32768..-129 | int16 | 0xD1
  5596. number_integer | -128..-33 | int8 | 0xD0
  5597. number_integer | -32..-1 | negative fixint | 0xE0..0xFF
  5598. number_integer | 0..127 | positive fixint | 0x00..0x7F
  5599. number_integer | 128..255 | uint 8 | 0xCC
  5600. number_integer | 256..65535 | uint 16 | 0xCD
  5601. number_integer | 65536..4294967295 | uint 32 | 0xCE
  5602. number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF
  5603. number_unsigned | 0..127 | positive fixint | 0x00..0x7F
  5604. number_unsigned | 128..255 | uint 8 | 0xCC
  5605. number_unsigned | 256..65535 | uint 16 | 0xCD
  5606. number_unsigned | 65536..4294967295 | uint 32 | 0xCE
  5607. number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF
  5608. number_float | *any value* | float 64 | 0xCB
  5609. string | *length*: 0..31 | fixstr | 0xA0..0xBF
  5610. string | *length*: 32..255 | str 8 | 0xD9
  5611. string | *length*: 256..65535 | str 16 | 0xDA
  5612. string | *length*: 65536..4294967295 | str 32 | 0xDB
  5613. array | *size*: 0..15 | fixarray | 0x90..0x9F
  5614. array | *size*: 16..65535 | array 16 | 0xDC
  5615. array | *size*: 65536..4294967295 | array 32 | 0xDD
  5616. object | *size*: 0..15 | fix map | 0x80..0x8F
  5617. object | *size*: 16..65535 | map 16 | 0xDE
  5618. object | *size*: 65536..4294967295 | map 32 | 0xDF
  5619. binary | *size*: 0..255 | bin 8 | 0xC4
  5620. binary | *size*: 256..65535 | bin 16 | 0xC5
  5621. binary | *size*: 65536..4294967295 | bin 32 | 0xC6
  5622. @note The mapping is **complete** in the sense that any JSON value type
  5623. can be converted to a MessagePack value.
  5624. @note The following values can **not** be converted to a MessagePack value:
  5625. - strings with more than 4294967295 bytes
  5626. - byte strings with more than 4294967295 bytes
  5627. - arrays with more than 4294967295 elements
  5628. - objects with more than 4294967295 elements
  5629. @note The following MessagePack types are not used in the conversion:
  5630. - float 32 (0xCA)
  5631. @note Any MessagePack output created @ref to_msgpack can be successfully
  5632. parsed by @ref from_msgpack.
  5633. @note If NaN or Infinity are stored inside a JSON number, they are
  5634. serialized properly. This behavior differs from the @ref dump()
  5635. function which serializes NaN or Infinity to `null`.
  5636. @param[in] j JSON value to serialize
  5637. @return MessagePack serialization as byte vector
  5638. @complexity Linear in the size of the JSON value @a j.
  5639. @liveexample{The example shows the serialization of a JSON value to a byte
  5640. vector in MessagePack format.,to_msgpack}
  5641. @sa http://msgpack.org
  5642. @sa @ref from_msgpack for the analogous deserialization
  5643. @sa @ref to_cbor(const basic_json& for the related CBOR format
  5644. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  5645. related UBJSON format
  5646. @since version 2.0.9
  5647. */
  5648. static std::vector<uint8_t> to_msgpack(const basic_json& j)
  5649. {
  5650. std::vector<uint8_t> result;
  5651. to_msgpack(j, result);
  5652. return result;
  5653. }
  5654. static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o)
  5655. {
  5656. binary_writer<uint8_t>(o).write_msgpack(j);
  5657. }
  5658. static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
  5659. {
  5660. binary_writer<char>(o).write_msgpack(j);
  5661. }
  5662. /*!
  5663. @brief create a UBJSON serialization of a given JSON value
  5664. Serializes a given JSON value @a j to a byte vector using the UBJSON
  5665. (Universal Binary JSON) serialization format. UBJSON aims to be more compact
  5666. than JSON itself, yet more efficient to parse.
  5667. The library uses the following mapping from JSON values types to
  5668. UBJSON types according to the UBJSON specification:
  5669. JSON value type | value/range | UBJSON type | marker
  5670. --------------- | --------------------------------- | ----------- | ------
  5671. null | `null` | null | `Z`
  5672. boolean | `true` | true | `T`
  5673. boolean | `false` | false | `F`
  5674. number_integer | -9223372036854775808..-2147483649 | int64 | `L`
  5675. number_integer | -2147483648..-32769 | int32 | `l`
  5676. number_integer | -32768..-129 | int16 | `I`
  5677. number_integer | -128..127 | int8 | `i`
  5678. number_integer | 128..255 | uint8 | `U`
  5679. number_integer | 256..32767 | int16 | `I`
  5680. number_integer | 32768..2147483647 | int32 | `l`
  5681. number_integer | 2147483648..9223372036854775807 | int64 | `L`
  5682. number_unsigned | 0..127 | int8 | `i`
  5683. number_unsigned | 128..255 | uint8 | `U`
  5684. number_unsigned | 256..32767 | int16 | `I`
  5685. number_unsigned | 32768..2147483647 | int32 | `l`
  5686. number_unsigned | 2147483648..9223372036854775807 | int64 | `L`
  5687. number_float | *any value* | float64 | `D`
  5688. string | *with shortest length indicator* | string | `S`
  5689. array | *see notes on optimized format* | array | `[`
  5690. object | *see notes on optimized format* | map | `{`
  5691. @note The mapping is **complete** in the sense that any JSON value type
  5692. can be converted to a UBJSON value.
  5693. @note The following values can **not** be converted to a UBJSON value:
  5694. - strings with more than 9223372036854775807 bytes (theoretical)
  5695. - unsigned integer numbers above 9223372036854775807
  5696. @note The following markers are not used in the conversion:
  5697. - `Z`: no-op values are not created.
  5698. - `C`: single-byte strings are serialized with `S` markers.
  5699. @note Any UBJSON output created @ref to_ubjson can be successfully parsed
  5700. by @ref from_ubjson.
  5701. @note If NaN or Infinity are stored inside a JSON number, they are
  5702. serialized properly. This behavior differs from the @ref dump()
  5703. function which serializes NaN or Infinity to `null`.
  5704. @note The optimized formats for containers are supported: Parameter
  5705. @a use_size adds size information to the beginning of a container and
  5706. removes the closing marker. Parameter @a use_type further checks
  5707. whether all elements of a container have the same type and adds the
  5708. type marker to the beginning of the container. The @a use_type
  5709. parameter must only be used together with @a use_size = true. Note
  5710. that @a use_size = true alone may result in larger representations -
  5711. the benefit of this parameter is that the receiving side is
  5712. immediately informed on the number of elements of the container.
  5713. @note If the JSON data contains the binary type, the value stored is a list
  5714. of integers, as suggested by the UBJSON documentation. In particular,
  5715. this means that serialization and the deserialization of a JSON
  5716. containing binary values into UBJSON and back will result in a
  5717. different JSON object.
  5718. @param[in] j JSON value to serialize
  5719. @param[in] use_size whether to add size annotations to container types
  5720. @param[in] use_type whether to add type annotations to container types
  5721. (must be combined with @a use_size = true)
  5722. @return UBJSON serialization as byte vector
  5723. @complexity Linear in the size of the JSON value @a j.
  5724. @liveexample{The example shows the serialization of a JSON value to a byte
  5725. vector in UBJSON format.,to_ubjson}
  5726. @sa http://ubjson.org
  5727. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  5728. analogous deserialization
  5729. @sa @ref to_cbor(const basic_json& for the related CBOR format
  5730. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  5731. @since version 3.1.0
  5732. */
  5733. static std::vector<uint8_t> to_ubjson(const basic_json& j,
  5734. const bool use_size = false,
  5735. const bool use_type = false)
  5736. {
  5737. std::vector<uint8_t> result;
  5738. to_ubjson(j, result, use_size, use_type);
  5739. return result;
  5740. }
  5741. static void to_ubjson(const basic_json& j, detail::output_adapter<uint8_t> o,
  5742. const bool use_size = false, const bool use_type = false)
  5743. {
  5744. binary_writer<uint8_t>(o).write_ubjson(j, use_size, use_type);
  5745. }
  5746. static void to_ubjson(const basic_json& j, detail::output_adapter<char> o,
  5747. const bool use_size = false, const bool use_type = false)
  5748. {
  5749. binary_writer<char>(o).write_ubjson(j, use_size, use_type);
  5750. }
  5751. /*!
  5752. @brief Serializes the given JSON object `j` to BSON and returns a vector
  5753. containing the corresponding BSON-representation.
  5754. BSON (Binary JSON) is a binary format in which zero or more ordered key/value pairs are
  5755. stored as a single entity (a so-called document).
  5756. The library uses the following mapping from JSON values types to BSON types:
  5757. JSON value type | value/range | BSON type | marker
  5758. --------------- | --------------------------------- | ----------- | ------
  5759. null | `null` | null | 0x0A
  5760. boolean | `true`, `false` | boolean | 0x08
  5761. number_integer | -9223372036854775808..-2147483649 | int64 | 0x12
  5762. number_integer | -2147483648..2147483647 | int32 | 0x10
  5763. number_integer | 2147483648..9223372036854775807 | int64 | 0x12
  5764. number_unsigned | 0..2147483647 | int32 | 0x10
  5765. number_unsigned | 2147483648..9223372036854775807 | int64 | 0x12
  5766. number_unsigned | 9223372036854775808..18446744073709551615| -- | --
  5767. number_float | *any value* | double | 0x01
  5768. string | *any value* | string | 0x02
  5769. array | *any value* | document | 0x04
  5770. object | *any value* | document | 0x03
  5771. binary | *any value* | binary | 0x05
  5772. @warning The mapping is **incomplete**, since only JSON-objects (and things
  5773. contained therein) can be serialized to BSON.
  5774. Also, integers larger than 9223372036854775807 cannot be serialized to BSON,
  5775. and the keys may not contain U+0000, since they are serialized a
  5776. zero-terminated c-strings.
  5777. @throw out_of_range.407 if `j.is_number_unsigned() && j.get<std::uint64_t>() > 9223372036854775807`
  5778. @throw out_of_range.409 if a key in `j` contains a NULL (U+0000)
  5779. @throw type_error.317 if `!j.is_object()`
  5780. @pre The input `j` is required to be an object: `j.is_object() == true`.
  5781. @note Any BSON output created via @ref to_bson can be successfully parsed
  5782. by @ref from_bson.
  5783. @param[in] j JSON value to serialize
  5784. @return BSON serialization as byte vector
  5785. @complexity Linear in the size of the JSON value @a j.
  5786. @liveexample{The example shows the serialization of a JSON value to a byte
  5787. vector in BSON format.,to_bson}
  5788. @sa http://bsonspec.org/spec.html
  5789. @sa @ref from_bson(detail::input_adapter&&, const bool strict) for the
  5790. analogous deserialization
  5791. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  5792. related UBJSON format
  5793. @sa @ref to_cbor(const basic_json&) for the related CBOR format
  5794. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  5795. */
  5796. static std::vector<uint8_t> to_bson(const basic_json& j)
  5797. {
  5798. std::vector<uint8_t> result;
  5799. to_bson(j, result);
  5800. return result;
  5801. }
  5802. /*!
  5803. @brief Serializes the given JSON object `j` to BSON and forwards the
  5804. corresponding BSON-representation to the given output_adapter `o`.
  5805. @param j The JSON object to convert to BSON.
  5806. @param o The output adapter that receives the binary BSON representation.
  5807. @pre The input `j` shall be an object: `j.is_object() == true`
  5808. @sa @ref to_bson(const basic_json&)
  5809. */
  5810. static void to_bson(const basic_json& j, detail::output_adapter<uint8_t> o)
  5811. {
  5812. binary_writer<uint8_t>(o).write_bson(j);
  5813. }
  5814. /*!
  5815. @copydoc to_bson(const basic_json&, detail::output_adapter<uint8_t>)
  5816. */
  5817. static void to_bson(const basic_json& j, detail::output_adapter<char> o)
  5818. {
  5819. binary_writer<char>(o).write_bson(j);
  5820. }
  5821. /*!
  5822. @brief create a JSON value from an input in CBOR format
  5823. Deserializes a given input @a i to a JSON value using the CBOR (Concise
  5824. Binary Object Representation) serialization format.
  5825. The library maps CBOR types to JSON value types as follows:
  5826. CBOR type | JSON value type | first byte
  5827. ---------------------- | --------------- | ----------
  5828. Integer | number_unsigned | 0x00..0x17
  5829. Unsigned integer | number_unsigned | 0x18
  5830. Unsigned integer | number_unsigned | 0x19
  5831. Unsigned integer | number_unsigned | 0x1A
  5832. Unsigned integer | number_unsigned | 0x1B
  5833. Negative integer | number_integer | 0x20..0x37
  5834. Negative integer | number_integer | 0x38
  5835. Negative integer | number_integer | 0x39
  5836. Negative integer | number_integer | 0x3A
  5837. Negative integer | number_integer | 0x3B
  5838. Byte string | binary | 0x40..0x57
  5839. Byte string | binary | 0x58
  5840. Byte string | binary | 0x59
  5841. Byte string | binary | 0x5A
  5842. Byte string | binary | 0x5B
  5843. UTF-8 string | string | 0x60..0x77
  5844. UTF-8 string | string | 0x78
  5845. UTF-8 string | string | 0x79
  5846. UTF-8 string | string | 0x7A
  5847. UTF-8 string | string | 0x7B
  5848. UTF-8 string | string | 0x7F
  5849. array | array | 0x80..0x97
  5850. array | array | 0x98
  5851. array | array | 0x99
  5852. array | array | 0x9A
  5853. array | array | 0x9B
  5854. array | array | 0x9F
  5855. map | object | 0xA0..0xB7
  5856. map | object | 0xB8
  5857. map | object | 0xB9
  5858. map | object | 0xBA
  5859. map | object | 0xBB
  5860. map | object | 0xBF
  5861. False | `false` | 0xF4
  5862. True | `true` | 0xF5
  5863. Null | `null` | 0xF6
  5864. Half-Precision Float | number_float | 0xF9
  5865. Single-Precision Float | number_float | 0xFA
  5866. Double-Precision Float | number_float | 0xFB
  5867. @warning The mapping is **incomplete** in the sense that not all CBOR
  5868. types can be converted to a JSON value. The following CBOR types
  5869. are not supported and will yield parse errors (parse_error.112):
  5870. - date/time (0xC0..0xC1)
  5871. - bignum (0xC2..0xC3)
  5872. - decimal fraction (0xC4)
  5873. - bigfloat (0xC5)
  5874. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  5875. - expected conversions (0xD5..0xD7)
  5876. - simple values (0xE0..0xF3, 0xF8)
  5877. - undefined (0xF7)
  5878. @warning CBOR allows map keys of any type, whereas JSON only allows
  5879. strings as keys in object values. Therefore, CBOR maps with keys
  5880. other than UTF-8 strings are rejected (parse_error.113).
  5881. @note Any CBOR output created @ref to_cbor can be successfully parsed by
  5882. @ref from_cbor.
  5883. @param[in] i an input in CBOR format convertible to an input adapter
  5884. @param[in] strict whether to expect the input to be consumed until EOF
  5885. (true by default)
  5886. @param[in] allow_exceptions whether to throw exceptions in case of a
  5887. parse error (optional, true by default)
  5888. @return deserialized JSON value; in case of a parse error and
  5889. @a allow_exceptions set to `false`, the return value will be
  5890. value_t::discarded.
  5891. @throw parse_error.110 if the given input ends prematurely or the end of
  5892. file was not reached when @a strict was set to true
  5893. @throw parse_error.112 if unsupported features from CBOR were
  5894. used in the given input @a v or if the input is not valid CBOR
  5895. @throw parse_error.113 if a string was expected as map key, but not found
  5896. @complexity Linear in the size of the input @a i.
  5897. @liveexample{The example shows the deserialization of a byte vector in CBOR
  5898. format to a JSON value.,from_cbor}
  5899. @sa http://cbor.io
  5900. @sa @ref to_cbor(const basic_json&) for the analogous serialization
  5901. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for the
  5902. related MessagePack format
  5903. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  5904. related UBJSON format
  5905. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  5906. consume input adapters, removed start_index parameter, and added
  5907. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  5908. since 3.2.0
  5909. */
  5910. template<typename InputType>
  5911. JSON_HEDLEY_WARN_UNUSED_RESULT
  5912. static basic_json from_cbor(InputType&& i,
  5913. const bool strict = true,
  5914. const bool allow_exceptions = true)
  5915. {
  5916. basic_json result;
  5917. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  5918. auto ia = detail::input_adapter(std::forward<InputType>(i));
  5919. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict);
  5920. return res ? result : basic_json(value_t::discarded);
  5921. }
  5922. /*!
  5923. @copydoc from_cbor(detail::input_adapter&&, const bool, const bool)
  5924. */
  5925. template<typename A1, typename A2,
  5926. detail::enable_if_t<std::is_constructible<detail::span_input_adapter, A1, A2>::value, int> = 0>
  5927. JSON_HEDLEY_WARN_UNUSED_RESULT
  5928. static basic_json from_cbor(A1 && a1, A2 && a2,
  5929. const bool strict = true,
  5930. const bool allow_exceptions = true)
  5931. {
  5932. basic_json result;
  5933. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  5934. const bool res = binary_reader<detail::input_buffer_adapter>(detail::span_input_adapter(std::forward<A1>(a1), std::forward<A2>(a2)).get()).sax_parse(input_format_t::cbor, &sdp, strict);
  5935. return res ? result : basic_json(value_t::discarded);
  5936. }
  5937. JSON_HEDLEY_WARN_UNUSED_RESULT
  5938. static basic_json from_cbor(detail::span_input_adapter&& i,
  5939. const bool strict = true,
  5940. const bool allow_exceptions = true)
  5941. {
  5942. basic_json result;
  5943. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  5944. const bool res = binary_reader<detail::input_buffer_adapter>(i.get()).sax_parse(input_format_t::cbor, &sdp, strict);
  5945. return res ? result : basic_json(value_t::discarded);
  5946. }
  5947. /*!
  5948. @brief create a JSON value from an input in MessagePack format
  5949. Deserializes a given input @a i to a JSON value using the MessagePack
  5950. serialization format.
  5951. The library maps MessagePack types to JSON value types as follows:
  5952. MessagePack type | JSON value type | first byte
  5953. ---------------- | --------------- | ----------
  5954. positive fixint | number_unsigned | 0x00..0x7F
  5955. fixmap | object | 0x80..0x8F
  5956. fixarray | array | 0x90..0x9F
  5957. fixstr | string | 0xA0..0xBF
  5958. nil | `null` | 0xC0
  5959. false | `false` | 0xC2
  5960. true | `true` | 0xC3
  5961. float 32 | number_float | 0xCA
  5962. float 64 | number_float | 0xCB
  5963. uint 8 | number_unsigned | 0xCC
  5964. uint 16 | number_unsigned | 0xCD
  5965. uint 32 | number_unsigned | 0xCE
  5966. uint 64 | number_unsigned | 0xCF
  5967. int 8 | number_integer | 0xD0
  5968. int 16 | number_integer | 0xD1
  5969. int 32 | number_integer | 0xD2
  5970. int 64 | number_integer | 0xD3
  5971. str 8 | string | 0xD9
  5972. str 16 | string | 0xDA
  5973. str 32 | string | 0xDB
  5974. array 16 | array | 0xDC
  5975. array 32 | array | 0xDD
  5976. map 16 | object | 0xDE
  5977. map 32 | object | 0xDF
  5978. bin 8 | binary | 0xC4
  5979. bin 16 | binary | 0xC5
  5980. bin 32 | binary | 0xC6
  5981. ext 8 | binary | 0xC7
  5982. ext 16 | binary | 0xC8
  5983. ext 32 | binary | 0xC9
  5984. fixext 1 | binary | 0xD4
  5985. fixext 2 | binary | 0xD5
  5986. fixext 4 | binary | 0xD6
  5987. fixext 8 | binary | 0xD7
  5988. fixext 16 | binary | 0xD8
  5989. negative fixint | number_integer | 0xE0-0xFF
  5990. @note Any MessagePack output created @ref to_msgpack can be successfully
  5991. parsed by @ref from_msgpack.
  5992. @param[in] i an input in MessagePack format convertible to an input
  5993. adapter
  5994. @param[in] strict whether to expect the input to be consumed until EOF
  5995. (true by default)
  5996. @param[in] allow_exceptions whether to throw exceptions in case of a
  5997. parse error (optional, true by default)
  5998. @return deserialized JSON value; in case of a parse error and
  5999. @a allow_exceptions set to `false`, the return value will be
  6000. value_t::discarded.
  6001. @throw parse_error.110 if the given input ends prematurely or the end of
  6002. file was not reached when @a strict was set to true
  6003. @throw parse_error.112 if unsupported features from MessagePack were
  6004. used in the given input @a i or if the input is not valid MessagePack
  6005. @throw parse_error.113 if a string was expected as map key, but not found
  6006. @complexity Linear in the size of the input @a i.
  6007. @liveexample{The example shows the deserialization of a byte vector in
  6008. MessagePack format to a JSON value.,from_msgpack}
  6009. @sa http://msgpack.org
  6010. @sa @ref to_msgpack(const basic_json&) for the analogous serialization
  6011. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  6012. related CBOR format
  6013. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for
  6014. the related UBJSON format
  6015. @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
  6016. the related BSON format
  6017. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  6018. consume input adapters, removed start_index parameter, and added
  6019. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  6020. since 3.2.0
  6021. */
  6022. template<typename InputType>
  6023. JSON_HEDLEY_WARN_UNUSED_RESULT
  6024. static basic_json from_msgpack(InputType&& i,
  6025. const bool strict = true,
  6026. const bool allow_exceptions = true)
  6027. {
  6028. basic_json result;
  6029. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  6030. auto ia = detail::input_adapter(std::forward<InputType>(i));
  6031. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict);
  6032. return res ? result : basic_json(value_t::discarded);
  6033. }
  6034. /*!
  6035. @copydoc from_msgpack(detail::input_adapter&&, const bool, const bool)
  6036. */
  6037. template<typename A1, typename A2,
  6038. detail::enable_if_t<std::is_constructible<detail::span_input_adapter, A1, A2>::value, int> = 0>
  6039. JSON_HEDLEY_WARN_UNUSED_RESULT
  6040. static basic_json from_msgpack(A1 && a1, A2 && a2,
  6041. const bool strict = true,
  6042. const bool allow_exceptions = true)
  6043. {
  6044. basic_json result;
  6045. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  6046. const bool res = binary_reader<detail::input_buffer_adapter>(detail::span_input_adapter(std::forward<A1>(a1), std::forward<A2>(a2)).get()).sax_parse(input_format_t::msgpack, &sdp, strict);
  6047. return res ? result : basic_json(value_t::discarded);
  6048. }
  6049. JSON_HEDLEY_WARN_UNUSED_RESULT
  6050. static basic_json from_msgpack(detail::span_input_adapter&& i,
  6051. const bool strict = true,
  6052. const bool allow_exceptions = true)
  6053. {
  6054. basic_json result;
  6055. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  6056. const bool res = binary_reader<detail::input_buffer_adapter>(i.get()).sax_parse(input_format_t::msgpack, &sdp, strict);
  6057. return res ? result : basic_json(value_t::discarded);
  6058. }
  6059. /*!
  6060. @brief create a JSON value from an input in UBJSON format
  6061. Deserializes a given input @a i to a JSON value using the UBJSON (Universal
  6062. Binary JSON) serialization format.
  6063. The library maps UBJSON types to JSON value types as follows:
  6064. UBJSON type | JSON value type | marker
  6065. ----------- | --------------------------------------- | ------
  6066. no-op | *no value, next value is read* | `N`
  6067. null | `null` | `Z`
  6068. false | `false` | `F`
  6069. true | `true` | `T`
  6070. float32 | number_float | `d`
  6071. float64 | number_float | `D`
  6072. uint8 | number_unsigned | `U`
  6073. int8 | number_integer | `i`
  6074. int16 | number_integer | `I`
  6075. int32 | number_integer | `l`
  6076. int64 | number_integer | `L`
  6077. string | string | `S`
  6078. char | string | `C`
  6079. array | array (optimized values are supported) | `[`
  6080. object | object (optimized values are supported) | `{`
  6081. @note The mapping is **complete** in the sense that any UBJSON value can
  6082. be converted to a JSON value.
  6083. @param[in] i an input in UBJSON format convertible to an input adapter
  6084. @param[in] strict whether to expect the input to be consumed until EOF
  6085. (true by default)
  6086. @param[in] allow_exceptions whether to throw exceptions in case of a
  6087. parse error (optional, true by default)
  6088. @return deserialized JSON value; in case of a parse error and
  6089. @a allow_exceptions set to `false`, the return value will be
  6090. value_t::discarded.
  6091. @throw parse_error.110 if the given input ends prematurely or the end of
  6092. file was not reached when @a strict was set to true
  6093. @throw parse_error.112 if a parse error occurs
  6094. @throw parse_error.113 if a string could not be parsed successfully
  6095. @complexity Linear in the size of the input @a i.
  6096. @liveexample{The example shows the deserialization of a byte vector in
  6097. UBJSON format to a JSON value.,from_ubjson}
  6098. @sa http://ubjson.org
  6099. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  6100. analogous serialization
  6101. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  6102. related CBOR format
  6103. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
  6104. the related MessagePack format
  6105. @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
  6106. the related BSON format
  6107. @since version 3.1.0; added @a allow_exceptions parameter since 3.2.0
  6108. */
  6109. template<typename InputType>
  6110. JSON_HEDLEY_WARN_UNUSED_RESULT
  6111. static basic_json from_ubjson(InputType&& i,
  6112. const bool strict = true,
  6113. const bool allow_exceptions = true)
  6114. {
  6115. basic_json result;
  6116. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  6117. auto ia = detail::input_adapter(std::forward<InputType>(i));
  6118. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict);
  6119. return res ? result : basic_json(value_t::discarded);
  6120. }
  6121. /*!
  6122. @copydoc from_ubjson(detail::input_adapter&&, const bool, const bool)
  6123. */
  6124. template<typename A1, typename A2,
  6125. detail::enable_if_t<std::is_constructible<detail::span_input_adapter, A1, A2>::value, int> = 0>
  6126. JSON_HEDLEY_WARN_UNUSED_RESULT
  6127. static basic_json from_ubjson(A1 && a1, A2 && a2,
  6128. const bool strict = true,
  6129. const bool allow_exceptions = true)
  6130. {
  6131. basic_json result;
  6132. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  6133. const bool res = binary_reader<detail::input_buffer_adapter>(detail::span_input_adapter(std::forward<A1>(a1), std::forward<A2>(a2)).get()).sax_parse(input_format_t::ubjson, &sdp, strict);
  6134. return res ? result : basic_json(value_t::discarded);
  6135. }
  6136. static basic_json from_ubjson(detail::span_input_adapter&& i,
  6137. const bool strict = true,
  6138. const bool allow_exceptions = true)
  6139. {
  6140. basic_json result;
  6141. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  6142. const bool res = binary_reader<detail::input_buffer_adapter>(i.get()).sax_parse(input_format_t::ubjson, &sdp, strict);
  6143. return res ? result : basic_json(value_t::discarded);
  6144. }
  6145. /*!
  6146. @brief Create a JSON value from an input in BSON format
  6147. Deserializes a given input @a i to a JSON value using the BSON (Binary JSON)
  6148. serialization format.
  6149. The library maps BSON record types to JSON value types as follows:
  6150. BSON type | BSON marker byte | JSON value type
  6151. --------------- | ---------------- | ---------------------------
  6152. double | 0x01 | number_float
  6153. string | 0x02 | string
  6154. document | 0x03 | object
  6155. array | 0x04 | array
  6156. binary | 0x05 | still unsupported
  6157. undefined | 0x06 | still unsupported
  6158. ObjectId | 0x07 | still unsupported
  6159. boolean | 0x08 | boolean
  6160. UTC Date-Time | 0x09 | still unsupported
  6161. null | 0x0A | null
  6162. Regular Expr. | 0x0B | still unsupported
  6163. DB Pointer | 0x0C | still unsupported
  6164. JavaScript Code | 0x0D | still unsupported
  6165. Symbol | 0x0E | still unsupported
  6166. JavaScript Code | 0x0F | still unsupported
  6167. int32 | 0x10 | number_integer
  6168. Timestamp | 0x11 | still unsupported
  6169. 128-bit decimal float | 0x13 | still unsupported
  6170. Max Key | 0x7F | still unsupported
  6171. Min Key | 0xFF | still unsupported
  6172. @warning The mapping is **incomplete**. The unsupported mappings
  6173. are indicated in the table above.
  6174. @param[in] i an input in BSON format convertible to an input adapter
  6175. @param[in] strict whether to expect the input to be consumed until EOF
  6176. (true by default)
  6177. @param[in] allow_exceptions whether to throw exceptions in case of a
  6178. parse error (optional, true by default)
  6179. @return deserialized JSON value; in case of a parse error and
  6180. @a allow_exceptions set to `false`, the return value will be
  6181. value_t::discarded.
  6182. @throw parse_error.114 if an unsupported BSON record type is encountered
  6183. @complexity Linear in the size of the input @a i.
  6184. @liveexample{The example shows the deserialization of a byte vector in
  6185. BSON format to a JSON value.,from_bson}
  6186. @sa http://bsonspec.org/spec.html
  6187. @sa @ref to_bson(const basic_json&) for the analogous serialization
  6188. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  6189. related CBOR format
  6190. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
  6191. the related MessagePack format
  6192. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  6193. related UBJSON format
  6194. */
  6195. template<typename InputType>
  6196. JSON_HEDLEY_WARN_UNUSED_RESULT
  6197. static basic_json from_bson(InputType&& i,
  6198. const bool strict = true,
  6199. const bool allow_exceptions = true)
  6200. {
  6201. basic_json result;
  6202. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  6203. auto ia = detail::input_adapter(std::forward<InputType>(i));
  6204. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict);
  6205. return res ? result : basic_json(value_t::discarded);
  6206. }
  6207. /*!
  6208. @copydoc from_bson(detail::input_adapter&&, const bool, const bool)
  6209. */
  6210. template<typename A1, typename A2,
  6211. detail::enable_if_t<std::is_constructible<detail::span_input_adapter, A1, A2>::value, int> = 0>
  6212. JSON_HEDLEY_WARN_UNUSED_RESULT
  6213. static basic_json from_bson(A1 && a1, A2 && a2,
  6214. const bool strict = true,
  6215. const bool allow_exceptions = true)
  6216. {
  6217. basic_json result;
  6218. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  6219. const bool res = binary_reader<detail::input_buffer_adapter>(detail::span_input_adapter(std::forward<A1>(a1), std::forward<A2>(a2)).get()).sax_parse(input_format_t::bson, &sdp, strict);
  6220. return res ? result : basic_json(value_t::discarded);
  6221. }
  6222. JSON_HEDLEY_WARN_UNUSED_RESULT
  6223. static basic_json from_bson(detail::span_input_adapter&& i,
  6224. const bool strict = true,
  6225. const bool allow_exceptions = true)
  6226. {
  6227. basic_json result;
  6228. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  6229. const bool res = binary_reader<detail::input_buffer_adapter>(i.get()).sax_parse(input_format_t::bson, &sdp, strict);
  6230. return res ? result : basic_json(value_t::discarded);
  6231. }
  6232. /// @}
  6233. //////////////////////////
  6234. // JSON Pointer support //
  6235. //////////////////////////
  6236. /// @name JSON Pointer functions
  6237. /// @{
  6238. /*!
  6239. @brief access specified element via JSON Pointer
  6240. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  6241. No bound checking is performed. Similar to @ref operator[](const typename
  6242. object_t::key_type&), `null` values are created in arrays and objects if
  6243. necessary.
  6244. In particular:
  6245. - If the JSON pointer points to an object key that does not exist, it
  6246. is created an filled with a `null` value before a reference to it
  6247. is returned.
  6248. - If the JSON pointer points to an array index that does not exist, it
  6249. is created an filled with a `null` value before a reference to it
  6250. is returned. All indices between the current maximum and the given
  6251. index are also filled with `null`.
  6252. - The special value `-` is treated as a synonym for the index past the
  6253. end.
  6254. @param[in] ptr a JSON pointer
  6255. @return reference to the element pointed to by @a ptr
  6256. @complexity Constant.
  6257. @throw parse_error.106 if an array index begins with '0'
  6258. @throw parse_error.109 if an array index was not a number
  6259. @throw out_of_range.404 if the JSON pointer can not be resolved
  6260. @liveexample{The behavior is shown in the example.,operatorjson_pointer}
  6261. @since version 2.0.0
  6262. */
  6263. reference operator[](const json_pointer& ptr)
  6264. {
  6265. return ptr.get_unchecked(this);
  6266. }
  6267. /*!
  6268. @brief access specified element via JSON Pointer
  6269. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  6270. No bound checking is performed. The function does not change the JSON
  6271. value; no `null` values are created. In particular, the special value
  6272. `-` yields an exception.
  6273. @param[in] ptr JSON pointer to the desired element
  6274. @return const reference to the element pointed to by @a ptr
  6275. @complexity Constant.
  6276. @throw parse_error.106 if an array index begins with '0'
  6277. @throw parse_error.109 if an array index was not a number
  6278. @throw out_of_range.402 if the array index '-' is used
  6279. @throw out_of_range.404 if the JSON pointer can not be resolved
  6280. @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
  6281. @since version 2.0.0
  6282. */
  6283. const_reference operator[](const json_pointer& ptr) const
  6284. {
  6285. return ptr.get_unchecked(this);
  6286. }
  6287. /*!
  6288. @brief access specified element via JSON Pointer
  6289. Returns a reference to the element at with specified JSON pointer @a ptr,
  6290. with bounds checking.
  6291. @param[in] ptr JSON pointer to the desired element
  6292. @return reference to the element pointed to by @a ptr
  6293. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  6294. begins with '0'. See example below.
  6295. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  6296. is not a number. See example below.
  6297. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  6298. is out of range. See example below.
  6299. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  6300. pointer @a ptr. As `at` provides checked access (and no elements are
  6301. implicitly inserted), the index '-' is always invalid. See example below.
  6302. @throw out_of_range.403 if the JSON pointer describes a key of an object
  6303. which cannot be found. See example below.
  6304. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  6305. See example below.
  6306. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  6307. changes in the JSON value.
  6308. @complexity Constant.
  6309. @since version 2.0.0
  6310. @liveexample{The behavior is shown in the example.,at_json_pointer}
  6311. */
  6312. reference at(const json_pointer& ptr)
  6313. {
  6314. return ptr.get_checked(this);
  6315. }
  6316. /*!
  6317. @brief access specified element via JSON Pointer
  6318. Returns a const reference to the element at with specified JSON pointer @a
  6319. ptr, with bounds checking.
  6320. @param[in] ptr JSON pointer to the desired element
  6321. @return reference to the element pointed to by @a ptr
  6322. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  6323. begins with '0'. See example below.
  6324. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  6325. is not a number. See example below.
  6326. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  6327. is out of range. See example below.
  6328. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  6329. pointer @a ptr. As `at` provides checked access (and no elements are
  6330. implicitly inserted), the index '-' is always invalid. See example below.
  6331. @throw out_of_range.403 if the JSON pointer describes a key of an object
  6332. which cannot be found. See example below.
  6333. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  6334. See example below.
  6335. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  6336. changes in the JSON value.
  6337. @complexity Constant.
  6338. @since version 2.0.0
  6339. @liveexample{The behavior is shown in the example.,at_json_pointer_const}
  6340. */
  6341. const_reference at(const json_pointer& ptr) const
  6342. {
  6343. return ptr.get_checked(this);
  6344. }
  6345. /*!
  6346. @brief return flattened JSON value
  6347. The function creates a JSON object whose keys are JSON pointers (see [RFC
  6348. 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
  6349. primitive. The original JSON value can be restored using the @ref
  6350. unflatten() function.
  6351. @return an object that maps JSON pointers to primitive values
  6352. @note Empty objects and arrays are flattened to `null` and will not be
  6353. reconstructed correctly by the @ref unflatten() function.
  6354. @complexity Linear in the size the JSON value.
  6355. @liveexample{The following code shows how a JSON object is flattened to an
  6356. object whose keys consist of JSON pointers.,flatten}
  6357. @sa @ref unflatten() for the reverse function
  6358. @since version 2.0.0
  6359. */
  6360. basic_json flatten() const
  6361. {
  6362. basic_json result(value_t::object);
  6363. json_pointer::flatten("", *this, result);
  6364. return result;
  6365. }
  6366. /*!
  6367. @brief unflatten a previously flattened JSON value
  6368. The function restores the arbitrary nesting of a JSON value that has been
  6369. flattened before using the @ref flatten() function. The JSON value must
  6370. meet certain constraints:
  6371. 1. The value must be an object.
  6372. 2. The keys must be JSON pointers (see
  6373. [RFC 6901](https://tools.ietf.org/html/rfc6901))
  6374. 3. The mapped values must be primitive JSON types.
  6375. @return the original JSON from a flattened version
  6376. @note Empty objects and arrays are flattened by @ref flatten() to `null`
  6377. values and can not unflattened to their original type. Apart from
  6378. this example, for a JSON value `j`, the following is always true:
  6379. `j == j.flatten().unflatten()`.
  6380. @complexity Linear in the size the JSON value.
  6381. @throw type_error.314 if value is not an object
  6382. @throw type_error.315 if object values are not primitive
  6383. @liveexample{The following code shows how a flattened JSON object is
  6384. unflattened into the original nested JSON object.,unflatten}
  6385. @sa @ref flatten() for the reverse function
  6386. @since version 2.0.0
  6387. */
  6388. basic_json unflatten() const
  6389. {
  6390. return json_pointer::unflatten(*this);
  6391. }
  6392. /// @}
  6393. //////////////////////////
  6394. // JSON Patch functions //
  6395. //////////////////////////
  6396. /// @name JSON Patch functions
  6397. /// @{
  6398. /*!
  6399. @brief applies a JSON patch
  6400. [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
  6401. expressing a sequence of operations to apply to a JSON) document. With
  6402. this function, a JSON Patch is applied to the current JSON value by
  6403. executing all operations from the patch.
  6404. @param[in] json_patch JSON patch document
  6405. @return patched document
  6406. @note The application of a patch is atomic: Either all operations succeed
  6407. and the patched document is returned or an exception is thrown. In
  6408. any case, the original value is not changed: the patch is applied
  6409. to a copy of the value.
  6410. @throw parse_error.104 if the JSON patch does not consist of an array of
  6411. objects
  6412. @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
  6413. attributes are missing); example: `"operation add must have member path"`
  6414. @throw out_of_range.401 if an array index is out of range.
  6415. @throw out_of_range.403 if a JSON pointer inside the patch could not be
  6416. resolved successfully in the current JSON value; example: `"key baz not
  6417. found"`
  6418. @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
  6419. "move")
  6420. @throw other_error.501 if "test" operation was unsuccessful
  6421. @complexity Linear in the size of the JSON value and the length of the
  6422. JSON patch. As usually only a fraction of the JSON value is affected by
  6423. the patch, the complexity can usually be neglected.
  6424. @liveexample{The following code shows how a JSON patch is applied to a
  6425. value.,patch}
  6426. @sa @ref diff -- create a JSON patch by comparing two JSON values
  6427. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  6428. @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
  6429. @since version 2.0.0
  6430. */
  6431. basic_json patch(const basic_json& json_patch) const
  6432. {
  6433. // make a working copy to apply the patch to
  6434. basic_json result = *this;
  6435. // the valid JSON Patch operations
  6436. enum class patch_operations {add, remove, replace, move, copy, test, invalid};
  6437. const auto get_op = [](const std::string & op)
  6438. {
  6439. if (op == "add")
  6440. {
  6441. return patch_operations::add;
  6442. }
  6443. if (op == "remove")
  6444. {
  6445. return patch_operations::remove;
  6446. }
  6447. if (op == "replace")
  6448. {
  6449. return patch_operations::replace;
  6450. }
  6451. if (op == "move")
  6452. {
  6453. return patch_operations::move;
  6454. }
  6455. if (op == "copy")
  6456. {
  6457. return patch_operations::copy;
  6458. }
  6459. if (op == "test")
  6460. {
  6461. return patch_operations::test;
  6462. }
  6463. return patch_operations::invalid;
  6464. };
  6465. // wrapper for "add" operation; add value at ptr
  6466. const auto operation_add = [&result](json_pointer & ptr, basic_json val)
  6467. {
  6468. // adding to the root of the target document means replacing it
  6469. if (ptr.empty())
  6470. {
  6471. result = val;
  6472. return;
  6473. }
  6474. // make sure the top element of the pointer exists
  6475. json_pointer top_pointer = ptr.top();
  6476. if (top_pointer != ptr)
  6477. {
  6478. result.at(top_pointer);
  6479. }
  6480. // get reference to parent of JSON pointer ptr
  6481. const auto last_path = ptr.back();
  6482. ptr.pop_back();
  6483. basic_json& parent = result[ptr];
  6484. switch (parent.m_type)
  6485. {
  6486. case value_t::null:
  6487. case value_t::object:
  6488. {
  6489. // use operator[] to add value
  6490. parent[last_path] = val;
  6491. break;
  6492. }
  6493. case value_t::array:
  6494. {
  6495. if (last_path == "-")
  6496. {
  6497. // special case: append to back
  6498. parent.push_back(val);
  6499. }
  6500. else
  6501. {
  6502. const auto idx = json_pointer::array_index(last_path);
  6503. if (JSON_HEDLEY_UNLIKELY(static_cast<size_type>(idx) > parent.size()))
  6504. {
  6505. // avoid undefined behavior
  6506. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  6507. }
  6508. // default case: insert add offset
  6509. parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
  6510. }
  6511. break;
  6512. }
  6513. // if there exists a parent it cannot be primitive
  6514. default: // LCOV_EXCL_LINE
  6515. assert(false); // LCOV_EXCL_LINE
  6516. }
  6517. };
  6518. // wrapper for "remove" operation; remove value at ptr
  6519. const auto operation_remove = [&result](json_pointer & ptr)
  6520. {
  6521. // get reference to parent of JSON pointer ptr
  6522. const auto last_path = ptr.back();
  6523. ptr.pop_back();
  6524. basic_json& parent = result.at(ptr);
  6525. // remove child
  6526. if (parent.is_object())
  6527. {
  6528. // perform range check
  6529. auto it = parent.find(last_path);
  6530. if (JSON_HEDLEY_LIKELY(it != parent.end()))
  6531. {
  6532. parent.erase(it);
  6533. }
  6534. else
  6535. {
  6536. JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found"));
  6537. }
  6538. }
  6539. else if (parent.is_array())
  6540. {
  6541. // note erase performs range check
  6542. parent.erase(static_cast<size_type>(json_pointer::array_index(last_path)));
  6543. }
  6544. };
  6545. // type check: top level value must be an array
  6546. if (JSON_HEDLEY_UNLIKELY(not json_patch.is_array()))
  6547. {
  6548. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  6549. }
  6550. // iterate and apply the operations
  6551. for (const auto& val : json_patch)
  6552. {
  6553. // wrapper to get a value for an operation
  6554. const auto get_value = [&val](const std::string & op,
  6555. const std::string & member,
  6556. bool string_type) -> basic_json &
  6557. {
  6558. // find value
  6559. auto it = val.m_value.object->find(member);
  6560. // context-sensitive error message
  6561. const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
  6562. // check if desired value is present
  6563. if (JSON_HEDLEY_UNLIKELY(it == val.m_value.object->end()))
  6564. {
  6565. JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'"));
  6566. }
  6567. // check if result is of type string
  6568. if (JSON_HEDLEY_UNLIKELY(string_type and not it->second.is_string()))
  6569. {
  6570. JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'"));
  6571. }
  6572. // no error: return value
  6573. return it->second;
  6574. };
  6575. // type check: every element of the array must be an object
  6576. if (JSON_HEDLEY_UNLIKELY(not val.is_object()))
  6577. {
  6578. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  6579. }
  6580. // collect mandatory members
  6581. const std::string op = get_value("op", "op", true);
  6582. const std::string path = get_value(op, "path", true);
  6583. json_pointer ptr(path);
  6584. switch (get_op(op))
  6585. {
  6586. case patch_operations::add:
  6587. {
  6588. operation_add(ptr, get_value("add", "value", false));
  6589. break;
  6590. }
  6591. case patch_operations::remove:
  6592. {
  6593. operation_remove(ptr);
  6594. break;
  6595. }
  6596. case patch_operations::replace:
  6597. {
  6598. // the "path" location must exist - use at()
  6599. result.at(ptr) = get_value("replace", "value", false);
  6600. break;
  6601. }
  6602. case patch_operations::move:
  6603. {
  6604. const std::string from_path = get_value("move", "from", true);
  6605. json_pointer from_ptr(from_path);
  6606. // the "from" location must exist - use at()
  6607. basic_json v = result.at(from_ptr);
  6608. // The move operation is functionally identical to a
  6609. // "remove" operation on the "from" location, followed
  6610. // immediately by an "add" operation at the target
  6611. // location with the value that was just removed.
  6612. operation_remove(from_ptr);
  6613. operation_add(ptr, v);
  6614. break;
  6615. }
  6616. case patch_operations::copy:
  6617. {
  6618. const std::string from_path = get_value("copy", "from", true);
  6619. const json_pointer from_ptr(from_path);
  6620. // the "from" location must exist - use at()
  6621. basic_json v = result.at(from_ptr);
  6622. // The copy is functionally identical to an "add"
  6623. // operation at the target location using the value
  6624. // specified in the "from" member.
  6625. operation_add(ptr, v);
  6626. break;
  6627. }
  6628. case patch_operations::test:
  6629. {
  6630. bool success = false;
  6631. JSON_TRY
  6632. {
  6633. // check if "value" matches the one at "path"
  6634. // the "path" location must exist - use at()
  6635. success = (result.at(ptr) == get_value("test", "value", false));
  6636. }
  6637. JSON_INTERNAL_CATCH (out_of_range&)
  6638. {
  6639. // ignore out of range errors: success remains false
  6640. }
  6641. // throw an exception if test fails
  6642. if (JSON_HEDLEY_UNLIKELY(not success))
  6643. {
  6644. JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump()));
  6645. }
  6646. break;
  6647. }
  6648. default:
  6649. {
  6650. // op must be "add", "remove", "replace", "move", "copy", or
  6651. // "test"
  6652. JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid"));
  6653. }
  6654. }
  6655. }
  6656. return result;
  6657. }
  6658. /*!
  6659. @brief creates a diff as a JSON patch
  6660. Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
  6661. be changed into the value @a target by calling @ref patch function.
  6662. @invariant For two JSON values @a source and @a target, the following code
  6663. yields always `true`:
  6664. @code {.cpp}
  6665. source.patch(diff(source, target)) == target;
  6666. @endcode
  6667. @note Currently, only `remove`, `add`, and `replace` operations are
  6668. generated.
  6669. @param[in] source JSON value to compare from
  6670. @param[in] target JSON value to compare against
  6671. @param[in] path helper value to create JSON pointers
  6672. @return a JSON patch to convert the @a source to @a target
  6673. @complexity Linear in the lengths of @a source and @a target.
  6674. @liveexample{The following code shows how a JSON patch is created as a
  6675. diff for two JSON values.,diff}
  6676. @sa @ref patch -- apply a JSON patch
  6677. @sa @ref merge_patch -- apply a JSON Merge Patch
  6678. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  6679. @since version 2.0.0
  6680. */
  6681. JSON_HEDLEY_WARN_UNUSED_RESULT
  6682. static basic_json diff(const basic_json& source, const basic_json& target,
  6683. const std::string& path = "")
  6684. {
  6685. // the patch
  6686. basic_json result(value_t::array);
  6687. // if the values are the same, return empty patch
  6688. if (source == target)
  6689. {
  6690. return result;
  6691. }
  6692. if (source.type() != target.type())
  6693. {
  6694. // different types: replace value
  6695. result.push_back(
  6696. {
  6697. {"op", "replace"}, {"path", path}, {"value", target}
  6698. });
  6699. return result;
  6700. }
  6701. switch (source.type())
  6702. {
  6703. case value_t::array:
  6704. {
  6705. // first pass: traverse common elements
  6706. std::size_t i = 0;
  6707. while (i < source.size() and i < target.size())
  6708. {
  6709. // recursive call to compare array values at index i
  6710. auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
  6711. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  6712. ++i;
  6713. }
  6714. // i now reached the end of at least one array
  6715. // in a second pass, traverse the remaining elements
  6716. // remove my remaining elements
  6717. const auto end_index = static_cast<difference_type>(result.size());
  6718. while (i < source.size())
  6719. {
  6720. // add operations in reverse order to avoid invalid
  6721. // indices
  6722. result.insert(result.begin() + end_index, object(
  6723. {
  6724. {"op", "remove"},
  6725. {"path", path + "/" + std::to_string(i)}
  6726. }));
  6727. ++i;
  6728. }
  6729. // add other remaining elements
  6730. while (i < target.size())
  6731. {
  6732. result.push_back(
  6733. {
  6734. {"op", "add"},
  6735. {"path", path + "/-"},
  6736. {"value", target[i]}
  6737. });
  6738. ++i;
  6739. }
  6740. break;
  6741. }
  6742. case value_t::object:
  6743. {
  6744. // first pass: traverse this object's elements
  6745. for (auto it = source.cbegin(); it != source.cend(); ++it)
  6746. {
  6747. // escape the key name to be used in a JSON patch
  6748. const auto key = json_pointer::escape(it.key());
  6749. if (target.find(it.key()) != target.end())
  6750. {
  6751. // recursive call to compare object values at key it
  6752. auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
  6753. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  6754. }
  6755. else
  6756. {
  6757. // found a key that is not in o -> remove it
  6758. result.push_back(object(
  6759. {
  6760. {"op", "remove"}, {"path", path + "/" + key}
  6761. }));
  6762. }
  6763. }
  6764. // second pass: traverse other object's elements
  6765. for (auto it = target.cbegin(); it != target.cend(); ++it)
  6766. {
  6767. if (source.find(it.key()) == source.end())
  6768. {
  6769. // found a key that is not in this -> add it
  6770. const auto key = json_pointer::escape(it.key());
  6771. result.push_back(
  6772. {
  6773. {"op", "add"}, {"path", path + "/" + key},
  6774. {"value", it.value()}
  6775. });
  6776. }
  6777. }
  6778. break;
  6779. }
  6780. default:
  6781. {
  6782. // both primitive type: replace value
  6783. result.push_back(
  6784. {
  6785. {"op", "replace"}, {"path", path}, {"value", target}
  6786. });
  6787. break;
  6788. }
  6789. }
  6790. return result;
  6791. }
  6792. /// @}
  6793. ////////////////////////////////
  6794. // JSON Merge Patch functions //
  6795. ////////////////////////////////
  6796. /// @name JSON Merge Patch functions
  6797. /// @{
  6798. /*!
  6799. @brief applies a JSON Merge Patch
  6800. The merge patch format is primarily intended for use with the HTTP PATCH
  6801. method as a means of describing a set of modifications to a target
  6802. resource's content. This function applies a merge patch to the current
  6803. JSON value.
  6804. The function implements the following algorithm from Section 2 of
  6805. [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396):
  6806. ```
  6807. define MergePatch(Target, Patch):
  6808. if Patch is an Object:
  6809. if Target is not an Object:
  6810. Target = {} // Ignore the contents and set it to an empty Object
  6811. for each Name/Value pair in Patch:
  6812. if Value is null:
  6813. if Name exists in Target:
  6814. remove the Name/Value pair from Target
  6815. else:
  6816. Target[Name] = MergePatch(Target[Name], Value)
  6817. return Target
  6818. else:
  6819. return Patch
  6820. ```
  6821. Thereby, `Target` is the current object; that is, the patch is applied to
  6822. the current value.
  6823. @param[in] apply_patch the patch to apply
  6824. @complexity Linear in the lengths of @a patch.
  6825. @liveexample{The following code shows how a JSON Merge Patch is applied to
  6826. a JSON document.,merge_patch}
  6827. @sa @ref patch -- apply a JSON patch
  6828. @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396)
  6829. @since version 3.0.0
  6830. */
  6831. void merge_patch(const basic_json& apply_patch)
  6832. {
  6833. if (apply_patch.is_object())
  6834. {
  6835. if (not is_object())
  6836. {
  6837. *this = object();
  6838. }
  6839. for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it)
  6840. {
  6841. if (it.value().is_null())
  6842. {
  6843. erase(it.key());
  6844. }
  6845. else
  6846. {
  6847. operator[](it.key()).merge_patch(it.value());
  6848. }
  6849. }
  6850. }
  6851. else
  6852. {
  6853. *this = apply_patch;
  6854. }
  6855. }
  6856. /// @}
  6857. };
  6858. /*!
  6859. @brief user-defined to_string function for JSON values
  6860. This function implements a user-defined to_string for JSON objects.
  6861. @param[in] j a JSON object
  6862. @return a std::string object
  6863. */
  6864. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  6865. std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j)
  6866. {
  6867. return j.dump();
  6868. }
  6869. } // namespace nlohmann
  6870. ///////////////////////
  6871. // nonmember support //
  6872. ///////////////////////
  6873. // specialization of std::swap, and std::hash
  6874. namespace std
  6875. {
  6876. /// hash value for JSON objects
  6877. template<>
  6878. struct hash<nlohmann::json>
  6879. {
  6880. /*!
  6881. @brief return a hash value for a JSON object
  6882. @since version 1.0.0
  6883. */
  6884. std::size_t operator()(const nlohmann::json& j) const
  6885. {
  6886. // a naive hashing via the string representation
  6887. const auto& h = hash<nlohmann::json::string_t>();
  6888. return h(j.dump());
  6889. }
  6890. };
  6891. /// specialization for std::less<value_t>
  6892. /// @note: do not remove the space after '<',
  6893. /// see https://github.com/nlohmann/json/pull/679
  6894. template<>
  6895. struct less<::nlohmann::detail::value_t>
  6896. {
  6897. /*!
  6898. @brief compare two value_t enum values
  6899. @since version 3.0.0
  6900. */
  6901. bool operator()(nlohmann::detail::value_t lhs,
  6902. nlohmann::detail::value_t rhs) const noexcept
  6903. {
  6904. return nlohmann::detail::operator<(lhs, rhs);
  6905. }
  6906. };
  6907. /*!
  6908. @brief exchanges the values of two JSON objects
  6909. @since version 1.0.0
  6910. */
  6911. template<>
  6912. inline void swap<nlohmann::json>(nlohmann::json& j1, nlohmann::json& j2) noexcept(
  6913. is_nothrow_move_constructible<nlohmann::json>::value and
  6914. is_nothrow_move_assignable<nlohmann::json>::value
  6915. )
  6916. {
  6917. j1.swap(j2);
  6918. }
  6919. } // namespace std
  6920. /*!
  6921. @brief user-defined string literal for JSON values
  6922. This operator implements a user-defined string literal for JSON objects. It
  6923. can be used by adding `"_json"` to a string literal and returns a JSON object
  6924. if no parse error occurred.
  6925. @param[in] s a string representation of a JSON object
  6926. @param[in] n the length of string @a s
  6927. @return a JSON object
  6928. @since version 1.0.0
  6929. */
  6930. JSON_HEDLEY_NON_NULL(1)
  6931. inline nlohmann::json operator "" _json(const char* s, std::size_t n)
  6932. {
  6933. return nlohmann::json::parse(s, s + n);
  6934. }
  6935. /*!
  6936. @brief user-defined string literal for JSON pointer
  6937. This operator implements a user-defined string literal for JSON Pointers. It
  6938. can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
  6939. object if no parse error occurred.
  6940. @param[in] s a string representation of a JSON Pointer
  6941. @param[in] n the length of string @a s
  6942. @return a JSON pointer object
  6943. @since version 2.0.0
  6944. */
  6945. JSON_HEDLEY_NON_NULL(1)
  6946. inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
  6947. {
  6948. return nlohmann::json::json_pointer(std::string(s, n));
  6949. }
  6950. #include <nlohmann/detail/macro_unscope.hpp>
  6951. #endif // INCLUDE_NLOHMANN_JSON_HPP_