cJSON

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.

Installation

linux: sudo apt install libcjson-dev
mac: brew install cjson
windows: Download source code from https://github.com/DaveGamble/cJSON and compile manually

Usage

cJSON 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.

Parsing a JSON string

#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.

Creating a JSON object

#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.

Working with JSON arrays

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.

Modifying JSON objects

cJSON_ReplaceItemInObject(root, "age", cJSON_CreateNumber(26));

Replaces the value of an existing key in a JSON object.

Writing JSON to a file

FILE *fp = fopen("data.json", "w");
fputs(cJSON_Print(root), fp);
fclose(fp);

Serializes a JSON object and writes it to a file.

Parsing JSON from 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.

Error Handling

cJSON_Parse returns NULL: Check JSON syntax and ensure the input string is valid.
Invalid type access: Use type checking functions like `cJSON_IsString`, `cJSON_IsNumber` before accessing values.
Memory leaks: Always call `cJSON_Delete` on allocated JSON objects and free printed strings.

Best Practices

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.