2

I tried out cJSON and discovered that even if I give an correct JSON followed by an incorrect JSON, it takes the entire content into its parse_buffer struct (in cJSON.c) and parses only the correct JSON. I can easily get the length of the total parsed content by doing something like: buffer.length in cJSON.c after the parsing is completed.

If I have a file which contains something like:

{
    "text": "HelloWorld!!"
}
{
    "text" : "incompletejson"

the cJSON puts the entire contents into its buffer and parses only the valid part.

If in my program I write:

//open file and read contents in buffer
/* Parse buffer into cJSON structure */
cJSON *root = cJSON_Parse(buffer);
char *text = cJSON_GetObjectItem(root, "text")->valuestring;
printf("text: %s\n", text);

it prints out HelloWorld!!.

Is there a way to get the length of just the parsed content i.e., the correct JSON that has been parsed? Is this at all possible in cJSON?

hw-135
  • 162
  • 1
  • 15
  • 2
    You want to use `cJSON_ParseWithOpts` instead of `cJSON_Parse`. Docs for `cJSON_Parse` say "*If an error occurs a pointer to the position of the error in the input string can be accessed using `cJSON_GetErrorPtr`. Note though that this can produce race conditions in multithreading scenarios, in that case it is better to use `cJSON_ParseWithOpts` with `return_parse_end`. By default, characters in the input string that follow the parsed JSON will not be considered as an error.*" – ikegami Nov 15 '19 at 17:28
  • @ikegami, could you provide an example of `cJSON_ParseWithOpts` with the length of parsed JSON? – hw-135 Nov 15 '19 at 17:42
  • `*return_parse_end - value` gives the offset at which it stopped parsing. Probably have to set the last parameter to `1`. – ikegami Nov 15 '19 at 17:44
  • @ikegami, what I meant was how could I access the values of `cJSON_GetErrorPtr` and `return_parse_end`. I have set the last parameter in `cJSON_ParseWithOpts` to 1 so that now invalid JSONs are throwing an error. But I not able to figure out how I can access the value where the valid JSON ended. – hw-135 Nov 18 '19 at 13:12
  • For example if I try and execute `printf("cjSON parse buffer: %s\n", cJSON_GetErrorPtr());` it gives me a Memory Access Error. – hw-135 Nov 18 '19 at 13:30
  • Re "*I not able to figure out how I can access the value where the valid JSON ended.*", `*return_parse_end - value` gives the offset at which it stopped parsing. (Those are names of `ParseWithOpts` parameters.) – ikegami Nov 18 '19 at 13:32

0 Answers0