截取json字符串算法

Posted qianbo_insist

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了截取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);

以上是关于截取json字符串算法的主要内容,如果未能解决你的问题,请参考以下文章

Java如何快速构造JSON字符串

mysql如何截取一个json字符串

JavaScript实用功能代码片段

片段(Java) | 机试题+算法思路+考点+代码解析 2023

将 JSON 字符串从片段传递到适配器的问题

mysql 类似json字符串截取,获取某个值