Json C语言递归遍历Json节点
Json
//程序用到了网上比较流行的Cjson开源库,可以在网上搜索下载,有两个文件(cjson.h和cjson.c),放到目录下即可
//递归遍历打印时,用{}区分数据是在哪个节点下,实际应用中若是要用通用的方式解析未知结构的json数据,可能把数据加载到Tree上会比较清晰。
// JsonTest.cpp : Defines the entry point for the console application. // XGZ.SZ.20251122 // Note:json递归遍历时需区分数据是否为一个节点下的 #include <stdio.h> #include "cJSON.h" void PrintjNode(cJSON *jNode) { int i; int size; cJSON * node = jNode; if(node == NULL) return; printf("%s:", node->string); switch(node->type) { case cJSON_False: printf("False\n"); break; case cJSON_True: printf("True\n"); break; case cJSON_NULL: printf("NULL\n"); break; case cJSON_Number: printf("%d\n", node->valueint); break; case cJSON_String: printf("%s\n", node->valuestring); break; case cJSON_Array: cJSON *nodeArray; size = cJSON_GetArraySize(node); printf("["); for(i = 0; i < size; i++) { nodeArray = cJSON_GetArrayItem(node, i); if(nodeArray == NULL) continue; printf("%s,", nodeArray->valuestring); } printf("]\n"); break; case cJSON_Object: //sub node printf("Object{\n", node->valuestring); break; default: printf("unknown\n", node->valuestring); } } void FindjNode(cJSON *jNode) { cJSON * node = jNode; if(node == NULL) return; PrintjNode(node); cJSON* jNodeChild = node->child; FindjNode(jNodeChild); if(jNodeChild != NULL) printf("}\n"); //XGZ:区分子节点数据和兄弟节点数据 cJSON* jNodeNext = node->next; FindjNode(jNodeNext); } int main(int argc, char* argv[]) { char text1[]="{\n\"name\": \"Jack (\\\"Bee\\\") Nimble\", \n\"format\": {\"type\": \"rect\", \n\"width\": 1920, \n\"height\": 1080, \n\"interlace\": false,\"frame rate\": 24\n}\n}"; //XGZ: 在原测试字符串中增加两个子节点 char text2[]="{\n\"name\": \"Jack (\\\"Bee\\\") Nimble\", \n\ \"format\": {\"type\": \"rect\", \n\"width\": 1920, \n\"height\": 1080, \n\"interlace\": false,\"frame rate\": 24\n},\ \n\"name\": \"Tom (\\\"Cow\\\") Nimble\", \n\ \"format\": {\"type\": \"Nothing\"\n}\ }"; cJSON *root = cJSON_Parse(text2); printf("\n=========================\n"); FindjNode(root); //XGZ: 找个文件测试 long len; char *pdata; FILE *fp = fopen("r:\\agent_vmw7.json","rb"); //FILE *fp = fopen("r:\\test2.json","rb"); fseek(fp,0,SEEK_END); len=ftell(fp); fseek(fp,0,SEEK_SET); pdata=new char[len+1]; fread(pdata,1,len,fp); fclose(fp); root = cJSON_Parse(pdata); printf("\n=========================\n"); FindjNode(root); delete pdata; return 0; }
程序运行的结果:

数据遍历,打印用{}区分子节点数据

浙公网安备 33010602011771号