Home > Software design >  How to encode JSON buffer in C?
How to encode JSON buffer in C?

Time:05-11

I have need of some advice.

I gather data from sensors on the analogue ports and I maintain data on the readings. I then format this data into a json style format which I then use to send it to cloud. Now the specific code I have for formatting the various values to json are held, not in a string of course, but in a character array using the int sprintf ( char * str, const char * format, ... ); method. Here is my routines that uses this code:

void StackData() {
    char buff[256];              

    sprintf(buff, "{\"id\":\"stat\",\"minHour\":%1i,\"maxHour\":%2i,\"minDay\":%3i,\"maxDay\":%4i,\"inHour\":%5lu,\"iinDay\":%6lu,\"inWeek\":%7lu}",
            minHour, maxHour, minDay, maxDay, AmpsHour, AmpsDay, AmpsWeek);
}

I would like to see how others might do this differently, or is this another way by using a specific library to do this?

PS: I have successfully used coreJSON library to parse JSON input

CodePudding user response:

What you have is reasonable, although an alternative might be some sort of result builder:

char buff[256] = { 0 }

jsonObjectOpen(buff);
jsonObjectInteger(buff,"minHour", minHour);
jsonObjectInteger(buff,"maxHour", maxHour);
jsonObjectClose(buff);

Basically each function is appending the necessary json elements to the buffer, and you'd need to implement functions for each data type (string, int, float), and of course, make sure you use the in the correct order.

I don't think this is more succinct, but if you are doing it more than a few times, especially for more complex structures, you might find it more readible and maintainable.

It's entirely possible there is an existing library that will help with this type of approach, also being mindful of ensuring that the buffer space isn't exceeded during the building process.

In other languages that have type detection, this is a lot easier, and I supposed you could always have a single function that takes a void pointer and a 'type' enum, but that could be more error prone for the sake of a marginally simpler API.

CodePudding user response:

I might be good idea to separate JSON object building from the encoding.

One of the existing JSON C-library do it by the following way:

json_t *item = json_object();
json_object_set_new(item, "id", json_string("stat"));
json_object_set_new(item, "minHour", json_integer(minHour));
json_object_set_new(item, "maxHour", json_integer(maxHour));
...


// Dump to console
json_dumpf(item, stdout, JSON_INDENT(4) | JSON_SORT_KEYS);

// Dump to file 
json_dumpf(item, file, JSON_COMPACT);
    
// Free allocated resources
json_decref(item);

The separation give some benefits. For example, encode formatting can be selected in one place.
And the same object can be easily encoded several ways (as in the example).

  • Related