C语言【微项目】|C语言【微项目16】—JSON值提取器V1版[纯字符串处理]【2022-03-17】


C语言【微项目16】—JSON值提取器V1版[纯字符串处理]【2022-03-17】

  • 1. tdtxjson.c
  • 2. 运行效果截图(长图)

【TDTX】
【C99】
【编译与运行环境】64位Windows操作系统,TDM-gcc 4.9.2 64bit(-std=c99)编译。
【问题描述】提取出JSON格式文件中的所有值。
【功能】:支持{ }、[ ] (有限支持)。其中[ ]只支持其中是键值对的数组!
【特注】 实现了一个JSON值的提取器,而不是实现了一个JSON转对象或者结构体
【版本】version 1.0
【将json文件与该代码的exe放在同一个目录文件夹下】
1. tdtxjson.c
#include #include #include void prase(const char* p,int n) { char key[n]; char value[n]; char t[n]; int count_left = 0; int count_right = 0; int ismatch = 0; int start = -1; int end = -1; int k = 0; int isvalue = https://www.it610.com/article/0; for(int i = 0; i < strlen(p); i++) { if(isvalue == 0 && p[i] ==':') { isvalue = https://www.it610.com/article/1; continue; } if(isvalue == 1) { if((p[i] ==',' || p[i] == '}') && (count_left==count_right && count_left == 0)) { t[k] = '\0'; printf("---->value is:%s\n",t); k = 0; t[k] = '\0'; isvalue = https://www.it610.com/article/0; continue; } if(p[i] =='{') { if(ismatch == 0) { ismatch = 1; } if(ismatch == 1) { count_left++; } } if(p[i] == '[') { if(ismatch == 0) { ismatch = 2; } if(ismatch == 2) { count_left++; } } if(p[i] == '}' || p[i] == ']') { if(ismatch == 2 && p[i] == ']') { count_right++; } if(ismatch == 1 && p[i] == '}') { count_right++; } } t[k++] = p[i]; //printf("count_left=%d,count_right=%d,ismatch=%d,i=%d\n",count_left,count_right,ismatch,i); if(count_left == count_right && count_left != 0) { t[k] = '\0'; printf("----》》》value is:%s\n",t); prase(t,n); puts("-----------------------------------------------------------------------------------"); k = 0; t[k] = '\0'; ismatch = 0; count_left = 0; count_right = 0; isvalue = https://www.it610.com/article/0; } } } }int main(int argc, char *argv[]) { char filename[100]; puts("输入要解析的文件名:"); gets(filename); int len = strlen(filename); filename[len] = '.'; filename[len+1] = 'j'; filename[len+1+1] = 's'; filename[len+1+1+1] = 'o'; filename[len+1+1+1+1] = 'n'; puts("\n被解析字符串:"); FILE* file = fopen(filename,"r"); char ch; char* p = (char*) malloc(sizeof(char)*0); int j = 0; while((ch=fgetc(file)) != EOF) { //printf("%c",ch); p = (char*)realloc(p,sizeof(char)*(++j)); p[j-1] = ch; } p[j] = '\0'; puts(p); prase(p,j); free(p); printf("\n\nok"); system("pause"); return 0; }

2. 运行效果截图(长图) C语言【微项目】|C语言【微项目16】—JSON值提取器V1版[纯字符串处理]【2022-03-17】
文章图片

C语言【微项目】|C语言【微项目16】—JSON值提取器V1版[纯字符串处理]【2022-03-17】
文章图片

C语言【微项目】|C语言【微项目16】—JSON值提取器V1版[纯字符串处理]【2022-03-17】
文章图片

C语言【微项目】|C语言【微项目16】—JSON值提取器V1版[纯字符串处理]【2022-03-17】
文章图片

C语言【微项目】|C语言【微项目16】—JSON值提取器V1版[纯字符串处理]【2022-03-17】
文章图片

C语言【微项目】|C语言【微项目16】—JSON值提取器V1版[纯字符串处理]【2022-03-17】
文章图片

【C语言【微项目】|C语言【微项目16】—JSON值提取器V1版[纯字符串处理]【2022-03-17】】C语言【微项目】|C语言【微项目16】—JSON值提取器V1版[纯字符串处理]【2022-03-17】
文章图片

    推荐阅读