json不合法的時候匿值,由字符串轉(zhuǎn)成json可能會導(dǎo)致程序復(fù)位,沒有試cjson是不是這樣赂摆,cjson也有別的bug挟憔。而C語言又不能try。為了防止意外的發(fā)送了不合法的json字符串烟号,就想到了校驗它合法性的方法绊谭。
在網(wǎng)上找到一個開源的項目,所以不用自己造輪子了:原項目地址
在此基礎(chǔ)上汪拥,自己改了下寫成了一個函數(shù):
uint8_t Jchecker(char* jcdata)
{
/*
Read STDIN. Exit with a message if the input is not well-formed JSON text.
jc will contain a JSON_checker with a maximum depth of 20.
*/
JSON_checker jc = new_JSON_checker(20);
for (int i=0;;i++)
{
int next_char = jcdata[i];
if (next_char <= 0) {
printf("JSON_checker_char:json correct\n");
return 0;
}
if (!JSON_checker_char(jc, next_char)) {
printf("JSON_checker_char: syntax error\n");
return 1;
}
}
if (!JSON_checker_done(jc)) {
printf("JSON_checker_end: syntax error\n");
return 1;
}
}
唯一有點坑的地方是达传,它對結(jié)尾的"}"不敏感,沒有也不會報錯迫筑。