How to write the json-c object into a file using C?

3.2k views Asked by At

I have created the jobj by using json-c library successfully with the json_object_to_json_string(jobj) where jobj hold the data which is in json format.

I am able to print jobj on the console by using printf: printf ("%s",json_object_to_json_string(jobj));

Now I need write the jobj data to file in "C" language as jobj we declared as json_object * jobj = json_object_new_object();

Request to provide the info on the above i.e. writing the jobj to a file (fwrite).

Below is the example code snipet https://linuxprograms.wordpress.com/2010/08/19/json_object_new_array/

Below is the code snipet

static void prepared_line_file(char* line)
{
FILE* fptr;
fptr =  fopen("/home/ubuntu/Desktop/sample.json", "a")
fwrite(line,sizeof(char),strlen(line),logfile);
}

main()
{
json_object_object_add(jobj,"USER", jarray);
prepared_line_file(jobj);
}

am i missing anything?

1

There are 1 answers

1
Joël Hecht On

I slightly modified the code you gave in order to write a readable string representing the json object to the file.

static void prepared_line_file(char* line)
{
    FILE* fptr;
    fptr = fopen("/home/ubuntu/Desktop/sample.json", "a");
    fwrite(line,sizeof(char),strlen(line),fptr);

    // fprintf(fptr, "%s", line); // would work too

    // The file should be closed when everything is written
    fclose(fptr);
}

main()
{
    // Will hold the string representation of the json object
    char *serialized_json;

    // Create an empty object : {}
    json_object * jobj = json_object_new_object();
    // Create an empty array : []
    json_object *jarray = json_object_new_array();

    // Put the array into the object : { "USER" : [] }
    json_object_object_add(jobj,"USER", jarray);

    // Transforms the binary representation into a string representation
    serialized_json = json_object_to_json_string(jobj);

    prepared_line_file(serialized_json);

    // Reports to the caller that everything was OK
    return EXIT_SUCCESS;
}