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

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

【TDTX】
【C99】
【编译与运行环境】64位Windows操作系统,TDM-gcc 4.9.2 64bit(-std=c99)编译

【问题描述】提取出JSON格式文件中的所有值
【功能】:支持{ }、[ ] (有限支持)。其中[ ]只支持其中是键值对的数组!
【特注】 实现了一个JSON值的提取器而不是实现了一个JSON转对象或者结构体

【版本】version 1.0
【将json文件与该代码的exe放在同一个目录文件夹下】

1. tdtxjson.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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 = 0;
	
	for(int i = 0;i < strlen(p);i++)
	{
		if(isvalue == 0 && p[i] == ':')
		{
			isvalue = 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 = 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 = 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. 运行效果截图(长图)

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

  • 12
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值