#include <stdio.h>
#include <stdlib.com>
#include “cJSON.h”
void print_cJSON_item(cJSON *item) {
if (!item) return;
switch ((item->type) & 255) {
case cJSON_True:
case cJSON_False:
printf("%s: %s\n", item->string, (item->type == cJSON_True) ? "true" : "false");
break;
case cJSON_Number:
printf("%s: %lf\n", item->string, item->valuedouble);
break;
case cJSON_String:
printf("%s: %s\n", item->string, item->valuestring);
break;
case cJSON_Array:
case cJSON_Object:
printf("%s:\n", item->string);
break;
case cJSON_Null:
printf("%s: null\n", item->string);
break;
default:
printf("Unhandled type: %d\n", item->type);
break;
}
}
void traverse_cJSON(cJSON *root) {
// Base case
if (!root) return;
// Recurse on objects and arrays
if (cJSON_IsObject(root) || cJSON_IsArray(root)) {
cJSON *child = root->child;
while (child) {
print_cJSON_item(child);
traverse_cJSON(child); // Recurse
child = child->next;
}
} else {
print_cJSON_item(root);
}
}
int main() {
const char *json_data = “{“name”:“John”,“age”:30,“cars”:[“Ford”,“BMW”,“Fiat”]}”;
cJSON *root = cJSON_Parse(json_data);
if (root == NULL) {
const char *error_ptr = cJSON_GetErrorPtr();
if (error_ptr != NULL) {
fprintf(stderr, "Error before: %s\n", error_ptr);
}
return 1;
}
traverse_cJSON(root);
cJSON_Delete(root);
return 0;
}