cJSON icon indicating copy to clipboard operation
cJSON copied to clipboard

Inputs not validated

Open bendrissou opened this issue 2 years ago • 2 comments

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

bendrissou avatar Oct 05 '23 20:10 bendrissou

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.

daschfg avatar Oct 06 '23 07:10 daschfg

This works well.

Thank you @daschfg.

bendrissou avatar Oct 06 '23 18:10 bendrissou