DaveGamble / cJSON

Ultralightweight JSON parser in ANSI C
MIT License
10.83k stars 3.22k forks source link

Inputs not validated #791

Open bendrissou opened 1 year ago

bendrissou commented 1 year ago

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);
    }
daschfg commented 1 year ago

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.

bendrissou commented 1 year ago

This works well.

Thank you @daschfg.