#include <stdio.h>#include<stdlib.h>#include"cJSON.h"voidPrintjson (Cjson * root)//to print the top-level key-value pairs of JSON in a recursive manner{ for(intI=0; I<cjson_getarraysize (root); i++)//traversing the outermost JSON key-value pair{Cjson* Item =Cjson_getarrayitem (root, I); if(Cjson_object = = Item->type)//recursive call Printjson if the value of the corresponding key is still cjson_objectPrintjson (item); Else //The value is not a JSON object to print out keys and values directly{printf ("%s->", item->string); printf ("%s\n", Cjson_print (item)); } }}intMain () {Char* Jsonstr ="{\ "semantic\": {\ " slots\": {\ "name\": \ "Zhang San \"}}, \ "Rc\": 0, \ "operation\": \ "call\", \ "service\": \ "telephone\", \ " Text\ ": \" call Zhang San \ "}"; Cjson* Root =NULL; Cjson* item = NULL;//Cjson ObjectRoot=Cjson_parse (JSONSTR); if(!root) {printf ("Error before: [%s]\n", Cjson_geterrorptr ()); } Else{printf ("%s\n","print JSON in a formatted way:"); printf ("%s\n\n", Cjson_print (root)); printf ("%s\n","To print the JSON in a unformatted manner:"); printf ("%s\n\n", cjson_printunformatted (root)); printf ("%s\n","get the name key-value pair step-by-step:"); printf ("%s\n","gets the Cjson object under semantic:"); Item= Cjson_getobjectitem (Root,"Semantic");//printf"%s\n", Cjson_print (item)); printf ("%s\n","gets the Cjson object under Slots"); Item= Cjson_getobjectitem (Item,"Slots"); printf ("%s\n", Cjson_print (item)); printf ("%s\n","get the Cjson object under name"); Item= Cjson_getobjectitem (Item,"name"); printf ("%s\n", Cjson_print (item)); printf ("%s:", item->string);//Take a look at the meaning of these two members in the structure of the Cjson objectprintf"%s\n", item->valuestring); printf ("\n%s\n","print JSON for all the most inner key-value pairs:"); Printjson (root); } return 0; }
Cjson parse.c