How to check if a string is a valid JSON before parsing it?
Hi, which method should I use to validate a string before parsing it with cJSON *root = cJSON_Parse(&data[0]);. I am experiencing crashes when the data is not correct after calling root->type==cJSON_Object.
Should I check the root structure value?
I think it is reasonable to check the return value before you using it. Or you could use cJSON_GetErrorPtr to get the error message when parsing falied.
I have developed a validate function in local, If most developers think that validate interface is necessary, then I might consider publishing it.
Hello. I have a similar "problem": for some reason (time to time) i got an invalid (packed) JSON string at output.
Could you publish validate interface for packaging / parsing of JSON strings?
Hi, I use cJSON_GetErrorPtr to get the error message, but it returns NULL. it means no wrong.
cJSON* a_json = cJSON_Parse(active_info);
// if (a_json == NULL)
// {
// const char *error_ptr = cJSON_GetErrorPtr();
// if (error_ptr != NULL)
// {
// sqb_utils_strncpy(a_info.error_msg, error_ptr, AI_ERROR_MSG_MAX_LEN);
// }
// log_i("a_info.e %s", a_info.error_msg);
// return a_info;
// }
error_ptr = cJSON_GetErrorPtr();
if (error_ptr != NULL)
{
sqb_utils_strncpy(a_info.error_msg, error_ptr, AI_ERROR_MSG_MAX_LEN);
log_i("a_info.e %s", a_info.error_msg);
}
log_i("no wrong");
Hi @mercurydarkork
I tried function cJSON_GetErrorPtr, but it's not working.
It seems that the parser would parse the first valid prefix and ignore the rest.
For example this input won't return any error:
{"var":null}}}}}
I also have a similar issue. If something accidentally gets passed to cJSON_Parse() that isn't the correct format it does not fail elegantly, it crashes. On my embedded system it actually causes a Kernel Panic and reboots the system ;-) A nice function like IsValidJSON() would be lovely.
Hi @youngie,
normally cJSON shouldn't crash on invalid input. But your system could crash if you use an invalid output.
How do you call cJSON_Parse and with which input?
Are you checking the result of cJSON_Parse against NULL before using it?