What is Jansson

            Jansson is C library for encoding/decoding/manipulating JSON data.
        

Installation (Ubuntu)


// Get Jansson.tar.gz
$ ./configure
$ make
$ sudo make install
$ make check        //Run test suite
        

Examples

Build Default Example


$ cd Jansson/examples
$ export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH
-l => library name
-I => header file include path
L => Library path
$ gcc simple_example.c L/usr/local/lib -I../src -ljansson
$ ./a.out
        

json_object_set_new(), json_object_foreach()


#include <jansson.h>
#include <stdio.h>

int main() {

    // Create a new JSON object
    json_t *object = json_object();
    
    // Add some key-value pairs to the object
    json_object_set_new (object, "name", json_string("ram"));
    json_object_set_new (object, "age", json_integer(30));

    // Print the original JSON object
    char *json_str = json_dumps (object, JSON_INDENT(4));
    printf("Original JSON object:\n%s\n\n", json_str);
    free (json_str);

    // Iterate over the key-value pairs in the object using json_object_foreach()
    const char *key;
    json_t *value;

    printf("Iterating over the JSON object:\n");
    json_object_foreach (object, key, value) {
        if (json_is_string(value)) {
            printf("Key: %s, Value (string): %s\n", key, json_string_value(value));
        } else if (json_is_integer(value)) {
            printf("Key: %s, Value (integer): %" JSON_INTEGER_FORMAT "\n", key, json_integer_value(value));
        }
    }

    // Modify the "city" key using json_object_set_new()
    json_object_set_new (object, "city", json_string("New Wonderland"));

    // Print the updated JSON object
    json_str = json_dumps(object, JSON_INDENT(4));
    printf ("\nUpdated JSON object after modifying 'city':\n%s\n", json_str);
    free (json_str);

    // Free the JSON object
    json_decref(object);

    return 0;
}