1

I'm reading and parsing a json file; all it works correctly if in the file there aren't new line; here's the code :

#include <json-c/json.h>
#include <stdio.h>
#include <string.h>

void parse_json(json_object * jobj);

int main(int argc, char* argv[]) {

    FILE *fp = fopen(argv[1], "r");
    char tmp[65000] = { 0x0 };
    if (fp == NULL) {
        perror("Error opening file");
        return (-1);
    } else {
        while (fp && fgets(tmp, sizeof(tmp), fp)) {

        }
    }
    fclose(fp);

    json_object * jobj = json_tokener_parse(tmp);
    parse_json(jobj);
}  

void parse_json(json_object * jobj) {

    printf("\n");
    enum json_type type;
    json_object_object_foreach(jobj, key, val)
    {
        type = json_object_get_type(val);
        switch (type) {
            case json_type_string:
            if (strcmp(key, "product") == 0) {
                printf("***** key found! ***** \n");
                printf("key: %s, value: %s \n", key,
                    json_object_get_string(val));
                printf("***** End keys ***** \n");
            } else {
                printf("key: %s, value: %s \n", key,
                    json_object_get_string(val));
            }
            break;
        }
    }
}

This is the working json:

{"product": "Live JSON generator"}

And this is the crashing json.

{
 "colors" :"blue"
}

So I think my error is int the reading file part.. What am I doing wrong?

MayurK
  • 1,925
  • 14
  • 27
DDBE
  • 325
  • 3
  • 13

1 Answers1

0

In case of file with new lines

while (fp && fgets(tmp, sizeof(tmp), fp))
{

}

tmp will be only having } as fgets overwrites the previous value. Thus json_tokener_parse will return NULL as you are passing invalid json tag.

You can do as below.

while (fp && fgets(tmp+strlen(tmp), sizeof(tmp)-strlen(tmp), fp))

or Have one more buffer and append the tmp to it everytime.

Note: I'm not sure if json_tokener_parse takes char * with \n as valid json tag. In that case you may need to manually parse out the \n from the buffer.

kiran Biradar
  • 12,700
  • 3
  • 19
  • 44