cJSON
cJSON copied to clipboard
Inputs not validated
Hi,
I would like to validate the input before parsing, in order to detect any errors and invalid inputs.
The current parser consumes the valid JSON prefix and ignores any remaining invalid sequences.
For example:
{"var":null}}}}}
When given the above input, the parser doesn't return any error, even when calling function cJSON_GetErrorPtr . See my code below.
cJSON *json = cJSON_Parse(input);
const char *error_ptr = cJSON_GetErrorPtr();
free(input);
if (json == NULL || error_ptr != NULL) {
printf("Invalid json.\n");
exit(1);
}
This is expected behaviour.
See Readme:
By default, characters in the input string that follow the parsed JSON will not be considered as an error.
If you want it to fail with an error, you could use cJSON_ParseWithOpts and set require_null_terminated to 1:
require_null_terminated, if set to 1 will make it an error if the input string contains data after the JSON.
This works well.
Thank you @daschfg.