cJSON icon indicating copy to clipboard operation
cJSON copied to clipboard

How to check if a string is a valid JSON before parsing it?

Open riccardobrue opened this issue 5 years ago • 6 comments

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?

riccardobrue avatar May 27 '20 07:05 riccardobrue

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.

Alanscut avatar May 27 '20 08:05 Alanscut

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?

stdenits avatar Oct 30 '20 10:10 stdenits

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");

mercurydarkork avatar May 18 '22 09:05 mercurydarkork

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}}}}}

bendrissou avatar Oct 05 '23 20:10 bendrissou

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.

youngie avatar Nov 11 '23 07:11 youngie

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?

daschfg avatar Nov 13 '23 18:11 daschfg