json.hpp 271 KB

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