/* Copyright (c) 2009 Dave Gamble Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/WelcometocJSON.cJSONaimstobethedumbestpossibleparserthatyoucangetyourjobdonewith.It's a single file of C, and a single header file.JSONisdescribedbesthere:http://www.json.org/It's like XML, but fat-free. You use it to move data around, store things, or justgenerallyrepresentyourprogram's state.Firstup,howdoIbuild?AddcJSON.ctoyourproject,andputcJSON.hsomewhereintheheadersearchpath.Forexample,tobuildthetestapp:gcccJSON.ctest.c-otest-lm./testAsalibrary,cJSONexiststotakeawayasmuchlegworkasitcan,butnotgetinyourway.Asapointofpragmatism(i.e.ignoringthetruth),I'm going to say that you can use itinoneoftwomodes:AutoandManual.Let's have a quick run-through.IliftedsomeJSONfromthispage:http://www.json.org/fatfree.htmlThatpageinspiredmetowritecJSON,whichisaparserthattriestosharethesamephilosophyasJSONitself.Simple,dumb,outoftheway.SomeJSON:{"name":"Jack (\"Bee\") Nimble","format":{"type":"rect","width":1920,"height":1080,"interlace":false,"frame rate":24}}Assumethatyougotthisfromafile,awebserver,ormagicJSONelves,whatever,youhaveachar*toit.EverythingisacJSONstruct.Getitparsed:cJSON*root=cJSON_Parse(my_json_string);Thisisanobject.We're in C. We don'thaveobjects.Butwedohavestructs.What's the framerate?cJSON*format=cJSON_GetObjectItem(root,"format");intframerate=cJSON_GetObjectItem(format,"frame rate")->valueint;Wanttochangetheframerate?cJSON_GetObjectItem(format,"frame rate")->valueint=25;Backtodisk?char*rendered=cJSON_Print(root);Finished?Deletetheroot(thistakescareofeverythingelse).cJSON_Delete(root);That's AUTO mode. If you'regoingtouseAutomode,youreallyoughttocheckpointersbeforeyoudereferencethem.Ifyouwanttoseehowyou'd build this struct in code?cJSON*root,*fmt;root=cJSON_CreateObject();cJSON_AddItemToObject(root,"name",cJSON_CreateString("Jack (\"Bee\") Nimble"));cJSON_AddItemToObject(root,"format",fmt=cJSON_CreateObject());cJSON_AddStringToObject(fmt,"type","rect");cJSON_AddNumberToObject(fmt,"width",1920);cJSON_AddNumberToObject(fmt,"height",1080);cJSON_AddFalseToObject(fmt,"interlace");cJSON_AddNumberToObject(fmt,"frame rate",24);Hopefullywecanagreethat's not a lot of code? There'snooverhead,nounnecessarysetup.Lookattest.cforabunchofniceexamples,mostlyallrippedoffthejson.orgsite,andafewfromelsewhere.Whataboutmanualmode?Firstupyouneedsomedetail.Let's cover how the cJSON objects represent the JSON data.cJSONdoesn't distinguish arrays from objects in handling; just type.EachcJSONhas,potentially,achild,siblings,value,aname.Therootobjecthas:ObjectTypeandaChildTheChildhasname"name",withvalue"Jack ("Bee") Nimble",andasibling:SiblinghastypeObject,name"format",andachild.ThatchildhastypeString,name"type",value"rect",andasibling:SiblinghastypeNumber,name"width",value1920,andasibling:SiblinghastypeNumber,name"height",value1080,andasibling:SiblinghstypeFalse,name"interlace",andasibling:SiblinghastypeNumber,name"frame rate",value24Here's the structure:typedefstructcJSON{structcJSON*next,*prev;structcJSON*child;inttype;char*valuestring;intvalueint;doublevaluedouble;char*string;}cJSON;Bydefaultallvaluesare0unlesssetbyvirtueofbeingmeaningful.next/previsadoublylinkedlistofsiblings.nexttakesyoutoyoursibling,prevtakesyoubackfromyoursiblingtoyou.Onlyobjectsandarrayshavea"child",andit's the head of the doubly linked list.A"child"entrywillhaveprev==0,butnextpotentiallypointson.Thelastsiblinghasnext=0.ThetypeexpressesNull/True/False/Number/String/Array/Object,allofwhichare#definedincJSON.hANumberhasvalueintandvaluedouble.Ifyou're expecting an int, read valueint, if not readvaluedouble.Anyentrywhichisinthelinkedlistwhichisthechildofanobjectwillhavea"string"whichisthe"name"oftheentry.WhenIsaid"name"intheaboveexample,that's "string"."string"istheJSONnameforthe'variable name'ifyouwill.Nowyoucantriviallywalkthelists,recursively,andparseasyouplease.YoucaninvokecJSON_ParsetogetcJSONtoparseforyou,andthenyoucantaketherootobject,andtraversethestructure(whichis,formally,anN-tree),andtokeniseasyouplease.Ifyouwantedtobuildacallbackstyleparser,thisishowyou'd do it (just an example, since these things are very specific):voidparse_and_callback(cJSON*item,constchar*prefix){while(item){char*newprefix=malloc(strlen(prefix)+strlen(item->name)+2);sprintf(newprefix,"%s/%s",prefix,item->name);intdorecurse=callback(newprefix,item->type,item);if(item->child&&dorecurse)parse_and_callback(item->child,newprefix);item=item->next;free(newprefix);}}Theprefixprocesswillbuildyouaseparatedlist,tosimplifyyourcallbackhandling.The'dorecurse'flagwouldletthecallbackdecidetohandlesub-arraysonit's own, orletyouinvokeitper-item.Fortheitemabove,yourcallbackmightlooklikethis:intcallback(constchar*name,inttype,cJSON*item){if(!strcmp(name,"name")){/* populate name */}elseif(!strcmp(name,"format/type"){/* handle "rect" */}elseif(!strcmp(name,"format/width"){/* 800 */}elseif(!strcmp(name,"format/height"){/* 600 */}elseif(!strcmp(name,"format/interlace"){/* false */}elseif(!strcmp(name,"format/frame rate"){/* 24 */}return1;}Alternatively,youmightliketoparseiteratively.You'd use:voidparse_object(cJSON*item){inti;for(i=0;i<cJSON_GetArraySize(item);i++){cJSON*subitem=cJSON_GetArrayItem(item,i);//handlesubitem.}}Or,forPROPERmanualmode:voidparse_object(cJSON*item){cJSON*subitem=item->child;while(subitem){//handlesubitemif(subitem->child)parse_object(subitem->child);subitem=subitem->next;}}Ofcourse,thisshouldlookfamiliar,sincethisisjustastripped-downversionofthecallback-parser.Thisshouldcovermostusesyou'll find for parsing. The rest should be possibletoinfer..andifindoubt,readthesource!There's not a lot of it! ;)IntermsofconstructingJSONdata,theexamplecodeaboveistherightwaytodoit.Youcan,ofcourse,handyoursub-objectstootherfunctionstopopulate.Also,ifyoufindauseforit,youcanmanuallybuildtheobjects.Forinstance,supposeyouwantedtobuildanarrayofobjects?cJSON*objects[24];cJSON*Create_array_of_anything(cJSON**items,intnum){inti;cJSON*prev,*root=cJSON_CreateArray();for(i=0;i<24;i++){if(!i)root->child=objects[i];elseprev->next=objects[i],objects[i]->prev=prev;prev=objects[i];}returnroot;}andsimply:Create_array_of_anything(objects,24);cJSONdoesn't make any assumptions about what order you create things in.Youcanattachtheobjects,asabove,andlateraddchildrentoeachofthoseobjects.AssoonasyoucallcJSON_Print,itrendersthestructuretotext.Thetest.ccodeshowshowtohandleabunchoftypicalcases.Ifyouuncommentthecode,it'll load, parse and print a bunch of test files, also from json.org,whicharemorecomplexthanI'd care to try and stash into a const char array[].EnjoycJSON!-DaveGamble,Aug2009