Language: C
Data / JSON
Jansson was created to provide a lightweight and easy-to-use library for handling JSON in C. It is designed with safety, clarity, and portability in mind, making it popular in C projects that require JSON parsing, configuration files, or data exchange with web services.
Jansson is a C library for encoding, decoding, and manipulating JSON data. It provides simple and intuitive APIs to parse JSON strings, build JSON objects, arrays, and write JSON to files or memory.
sudo apt install libjansson-devbrew install janssonDownload precompiled binaries from https://digip.org/jansson/Jansson allows you to parse JSON strings into objects, manipulate them (add/remove keys, iterate arrays), and serialize JSON objects back into strings or files. It handles memory management safely and supports Unicode.
#include <jansson.h>
#include <stdio.h>
int main() {
const char *text = "{\"name\": \"Alice\", \"age\": 30}";
json_error_t error;
json_t *root = json_loads(text, 0, &error);
if(!root) {
fprintf(stderr, "Error parsing JSON: %s\n", error.text);
return 1;
}
const char *name = json_string_value(json_object_get(root, "name"));
printf("Name: %s\n", name);
json_decref(root);
return 0;
}Parses a JSON string into a `json_t` object, retrieves the 'name' value, prints it, and frees memory.
#include <jansson.h>
json_t *root = json_object();
json_object_set_new(root, "name", json_string("Bob"));
json_object_set_new(root, "age", json_integer(25));
char *text = json_dumps(root, JSON_INDENT(2));
printf("%s\n", text);
free(text);
json_decref(root);Builds a JSON object programmatically, serializes it as a string, prints it, and frees memory.
const char *key;
json_t *value;
json_object_foreach(root, key, value) {
printf("%s: %s\n", key, json_string_value(value));
}Iterates over all key-value pairs in a JSON object.
json_t *arr = json_array();
json_array_append_new(arr, json_string("apple"));
json_array_append_new(arr, json_string("banana"));
for(size_t i = 0; i < json_array_size(arr); i++) {
printf("%s\n", json_string_value(json_array_get(arr, i)));
}
json_decref(arr);Creates a JSON array, appends items, iterates over them, and frees memory.
FILE *fp = fopen("data.json", "w");
json_dumpf(root, fp, JSON_INDENT(2));
fclose(fp);Writes a JSON object to a file in a human-readable format.
json_error_t error;
json_t *root = json_load_file("data.json", 0, &error);Loads a JSON object directly from a file and handles parsing errors.
Always check the return value of `json_loads` or `json_load_file` to catch parsing errors.
Use `json_decref` to free JSON objects when no longer needed.
Prefer `json_object_set_new` and `json_array_append_new` to automatically manage memory for new items.
Use `json_dumps` or `json_dumpf` with indentation options for readable JSON output.
Handle Unicode strings carefully; Jansson internally uses UTF-8 encoding.