最近项目中需要对一个流进行处理,其中需要一个提取json串的功能,没有找到相关开源的方法,于是手写了一个。
因为json串开始结束是以 {} 作为分割的,但是json里面有嵌套包含 {} 的情况。如果能保证截取的字符串里面的 { 和 } 的数量是相同的就可以认为是json格式。具体思路就是从流中截取第1个 { 和第1个 } 中间的字符串 ,如果字符串里面 { 和 } 数量相等,就认为截取成功;如果不相等,那就截取流中第1个{ 和 第 “1+1”个 } 中间的字符串,依次递增,直到 { 和 } 的数量相等为止。
下面是实现代码,功能不太完善,只能截取流中第一个json,如果需要截取流中所有的json,再次封装一下轮训就可以。
/*****************************************************************************
* Function: <name> extract_json
* Description: 从string里面截取第一个json串
* Parameter: 输入string,截取的json
* Returns: 截取的json
* Others: 只截取第一个json,如完全解析,轮训即可
*****************************************************************************/
std::string extract_json(std::string &str_in,std::string &str_out)
{
str_out = "";
int end_time = 1;//string中截取的}的个数,初始为1
do
{
int _start = str_in.find("{");//第一个{的位置
if(-1 == _start)
return "";
int _end = 0;
for(int i = 0; i<end_time; i++)//第 end_time个}的位置
{
_end = str_in.find("}",_end);
if(-1 == _end)
return "";
_end++;
}
std::string temp = str_in.substr(_start,_end - _start);//第一个{和第end_time个}之间的字符串
//检测temp字符串含有的{个数
int start_num = 0;
do
{
int comma_n = 0;
comma_n = temp.find("{");
if(-1 == comma_n)
break;
temp.erase(0, comma_n + 1);
start_num++;
} while (true);
//检测temp字符串含有的}个数
int end_num = 0;
temp = str_in.substr(_start,_end - _start);
do
{
int comma_n = 0;
comma_n = temp.find("}");
if(-1 == comma_n)
break;
temp.erase(0, comma_n + 1);
end_num++;
} while (true);
if(start_num == end_num)//如果{和}的数量相等,则判断为标准json
{
str_out = str_in.substr(_start,_end - _start + 1);
return str_out;
}
else//如不等,重新截取temp,下次多截取一个}
{
end_time ++;
}
}while(true);
}