📌 What is cJSON?
cJSON is a lightweight C library used to parse and generate JSON data. It is widely used in embedded systems like ESP32 due to its small size and simplicity.
⚙️ Installation
git clone https://github.com/davegamble/cjson
#include "cJSON.h"
🟢 Create JSON
cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "name", "John");
cJSON_AddNumberToObject(root, "age", 25);
char *json = cJSON_Print(root);
printf("%s\n", json);
cJSON_Delete(root);
free(json);
🔍 Parse JSON
char *data = "{\"name\":\"John\",\"age\":25}";
cJSON *root = cJSON_Parse(data);
cJSON *name = cJSON_GetObjectItem(root, "name");
printf("%s\n", name->valuestring);
cJSON_Delete(root);
📚 Arrays
cJSON *arr = cJSON_CreateArray(); cJSON_AddItemToArray(arr, cJSON_CreateNumber(10)); cJSON_AddItemToArray(arr, cJSON_CreateNumber(20));
📦 Nested JSON
cJSON *root = cJSON_CreateObject(); cJSON *addr = cJSON_CreateObject(); cJSON_AddStringToObject(addr, "city", "Kolkata"); cJSON_AddItemToObject(root, "address", addr);
🚀 Advanced Usage
cJSON_ReplaceItemInObject(root, "age", cJSON_CreateNumber(30));
if (cJSON_IsString(name)) {
printf("Valid\n");
}
⚠️ Memory Management
- Always use cJSON_Delete()
- Free strings using free()
- Avoid memory leaks
🔌 ESP32 Example
cJSON *root = cJSON_CreateObject(); cJSON_AddNumberToObject(root, "temp", 28.5); char *json = cJSON_PrintUnformatted(root); // send via HTTP cJSON_Delete(root); free(json);
🟢 Create Functions
cJSON *cJSON_CreateObject(void);
cJSON *cJSON_CreateArray(void);
cJSON *cJSON_CreateString(const char *string);
cJSON *cJSON_CreateNumber(double num);
cJSON *cJSON_CreateBool(cJSON_bool b);
📥 Access Functions
cJSON *cJSON_GetObjectItem(const cJSON *, const char *);
cJSON *cJSON_GetArrayItem(const cJSON *, int);
int cJSON_GetArraySize(const cJSON *);
✏️ Modify Functions
cJSON_AddItemToObject()
cJSON_AddItemToArray()
cJSON_ReplaceItemInObject()
cJSON_DeleteItemFromObject()
🖨️ Print Functions
char *cJSON_Print(const cJSON *);
char *cJSON_PrintUnformatted(const cJSON *);
⚠️ Memory Functions
void cJSON_Delete(cJSON *);