Decoding JSON data

The following code sample uses the libjson library to parse a JSON string and store the fields in a data structure for later use.

The extract_file_info() function parses the passed-in string, which stores information about a file, and writes the various fields into a file_t structure that the caller can then read using the pointer it provided to the function.

#include <string.h>
#include <stdio.h>
#include <sys/json.h>
    
typedef struct {
    const char *path;
    int type;
    long long size;
} info_t;

typedef struct {
    int id;
    info_t info;
} file_t;

bool extract_file_info(const char *str, file_t *file_info)
{
    json_decoder_t *dec = json_decoder_create();
    json_decoder_parse_json_str(dec, str);
    
    // Pre-initialise the structure so that omitted optional fields have default values
    memset(file_info, 0, sizeof(*file_info));
    file_info->info.type = 1;

    // Extract data from the decoder. One can choose to check each call for success if
    // it's important to report precise errors. Alternatively, as is done here, one can 
    // ignore intermediate errors and just check the final status.
    json_decoder_push_object(dec, NULL, false);
    json_decoder_get_int(dec, "id", &file_info->id, false);
    
    json_decoder_push_object(dec, "info", false);
    json_decoder_get_string(dec, "path", &file_info->info.path, false);
    // The 'type' is optional. If not present, the call will fail but will not affect
    // the decoder's status. We've initialized the field to the value it should have
    // if not present, so it doesn't have to be there.
    json_decoder_get_int(dec, "type", &file_info->info.type, true);
    // The 'size' is also optional.
    json_decoder_get_int_ll(dec, "size", &file_info->info.size, true);

    json_decoder_error_t status = json_decoder_get_status(dec, true);

    // While one might usually use a decoder to decode multiple strings, we just free it
    json_decoder_destroy(dec);

    // If everything above has succeeded, json_decoder_get_status() will return 
    // JSON_DECODER_OK
    if ( status != JSON_DECODER_OK ) {
        printf("Data extraction failed\n");
        return false;
    }

    return true;
}