截取json字符串算法

json字符串

json字符串样式如下:
{“type”:“drawInfo”, “data” : {}}
里面不管有多少对象,我们都要截取里面data的数据内容,怎么计算?
//{“type”:“mouse”, “id” : “zMeNT7TJL”, “roomId” : 222, “fileId” : 64, “imgIndex” : 0,
// “data” : {“x”:“0.068”, “y” : “0.160”}, “attr” : {“size”:1, “color” : “#FF0000”, “zoom” : 1}}}
//{“type”:“drawInfo”, “data” : {“type”:“line”, “id” : “s4XiVYhXV”, “roomId” : 222, “fileId” : 64,
// “imgIndex” : 0, “data” : {“x”:[“0.068”, “0.068”, “0.071”, “0.078”, “0.083”, “0.095”, “0.110”, “0.125”,
// “0.140”, “0.162”, “0.173”, “0.178”, “0.187”, “0.192”, “0.194”, “0.198”, “0.198”, “0.199”, “0.203”,
// “0.207”, “0.209”, “0.212”, “0.216”, “0.218”, “0.222”, “0.228”, “0.231”, “0.234”, “0.238”, “0.242”,
// “0.243”, “0.248”, “0.251”, “0.256”, “0.259”, “0.261”, “0.262”],
// “y” : [“0.163”, “0.165”, “0.171”, “0.183”, “0.194”, “0.209”, “0.236”, “0.252”, “0.269”, “0.287”,
// “0.301”, “0.307”, “0.323”, “0.330”, “0.336”, “0.339”, “0.341”, “0.341”, “0.347”, “0.352”, “0.359”,
// “0.363”, “0.370”, “0.376”, “0.383”, “0.392”, “0.399”, “0.405”, “0.412”, “0.416”, “0.421”, “0.430”,
// “0.434”, “0.445”, “0.452”, “0.454”, “0.457”]},
// “attr” : {“size”:1, “color” : “#FF0000”, “zoom” : 1}}}

算法如下

1 计算‘{’ 的数据,一直到‘}’ 为止,统计有多少个 { ,就一直搜索字符串到有第几个’}’ 结束
2 截取字符串

其他

如果该data是一直到内容结束,其最简单的方法是截取到最后一个‘}’

static int data_extract(int start, string &d, string &out)
{
	size_t len = d.size();
	if (len < start)
		return -1;
	if (d[len - 1] != '}')
		return -1;
	//for (size_t i = 23; i < len; i++)
	//{
	size_t i = start;
	while (d[i++] != '{' && (i < len - 1));
	out = d.substr(i - 1);
	out.pop_back();
	return 0;
}

其中start是跳过的最少的字符串量,对于
{“type”:“drawinfo” ,“data” : {“x”:" xxxxxxx",y:“yyyyyy”}}来说,可以跳过至少23字节
调用
data_extract( 23,x,y);

你可能感兴趣的:(c++,json,截取)