Language: C
Data / JSON
cJSON was created by Dave Gamble to provide a minimalistic, easy-to-use C library for handling JSON data. It is widely used in projects that need a small footprint and fast JSON parsing without external dependencies.
cJSON is a lightweight C library for parsing, printing, and manipulating JSON data. It is designed to be simple, fast, and portable, making it ideal for embedded systems and performance-critical applications.
sudo apt install libcjson-devbrew install cjsonDownload source code from https://github.com/DaveGamble/cJSON and compile manuallycJSON allows you to parse JSON strings into C structures, traverse and modify JSON objects and arrays, and serialize them back into strings or files. It is suitable for both simple and complex JSON handling.
#include <stdio.h>
#include <cjson/cJSON.h>
int main() {
const char *text = "{\"name\":\"Alice\",\"age\":30}";
cJSON *root = cJSON_Parse(text);
if (!root) {
printf("Error parsing JSON\n");
return 1;
}
cJSON *name = cJSON_GetObjectItem(root, "name");
printf("Name: %s\n", name->valuestring);
cJSON_Delete(root);
return 0;
}Parses a JSON string, retrieves the 'name' value, prints it, and frees memory.
#include <cjson/cJSON.h>
cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "name", "Bob");
cJSON_AddNumberToObject(root, "age", 25);
char *text = cJSON_Print(root);
printf("%s\n", text);
cJSON_free(text);
cJSON_Delete(root);Creates a JSON object programmatically, prints it as a string, and frees memory.
cJSON *arr = cJSON_CreateArray();
cJSON_AddItemToArray(arr, cJSON_CreateString("apple"));
cJSON_AddItemToArray(arr, cJSON_CreateString("banana"));
for(int i = 0; i < cJSON_GetArraySize(arr); i++) {
cJSON *item = cJSON_GetArrayItem(arr, i);
printf("%s\n", item->valuestring);
}
cJSON_Delete(arr);Creates a JSON array, adds elements, iterates over them, and deletes the array.
cJSON_ReplaceItemInObject(root, "age", cJSON_CreateNumber(26));Replaces the value of an existing key in a JSON object.
FILE *fp = fopen("data.json", "w");
fputs(cJSON_Print(root), fp);
fclose(fp);Serializes a JSON object and writes it to a file.
FILE *fp = fopen("data.json", "r");
fseek(fp, 0, SEEK_END);
long length = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *data = malloc(length + 1);
fread(data, 1, length, fp);
data[length] = '\0';
cJSON *root = cJSON_Parse(data);
free(data);
fclose(fp);Reads a JSON file into memory, parses it, and handles cleanup.
Always check return values from `cJSON_Parse` to handle parsing errors.
Use `cJSON_Delete` to free memory after creating or parsing objects.
Use `cJSON_AddItemToObject` and `cJSON_AddItemToArray` to manage memory automatically.
Use `cJSON_Print` or `cJSON_PrintBuffered` for serializing JSON to strings.
Avoid memory leaks by freeing both JSON objects and allocated strings properly.