The cJSON library is a simple and concise JSON parser for the C language. It provides the capability to parse, print, and write JSON data with ease. For developers working in C, understanding how to effectively manage JSON data is essential, especially when dealing with modern web APIs and configuration files. In this post, we’ll dive into cJSON examples that demonstrate how to parse a JSON file, write data to a JSON file, and print a JSON object in C. These examples are designed to be clear, concise, and easy to follow for better learning and readability.
Table of Contents
Include Headers
Include the below headers to manipulate JSON data in C.
#include <stdio.h> #include <stdlib.h> #include "cJSON.h"
Parse JSON Object Example
Let’s start by parsing a simple JSON object using cJSON:
void parse_json_object(const char *json_string) { cJSON *json = cJSON_Parse(json_string); if (json == NULL) { const char *error_ptr = cJSON_GetErrorPtr(); if (error_ptr != NULL) { fprintf(stderr, "Error before: %s\n", error_ptr); } return; } const cJSON *name = cJSON_GetObjectItemCaseSensitive(json, "name"); if (cJSON_IsString(name) && (name->valuestring != NULL)) { printf("Name: %s\n", name->valuestring); } cJSON_Delete(json); } // Example usage const char *my_json = "{\"name\":\"John\"}"; parse_json_object(my_json);
Output:
Name: John
In this example, we define a function parse_json_object
that takes a JSON string, parses it, and prints the value of the “name” attribute. It also handles potential errors by checking if cJSON_Parse
returns a NULL pointer.
Read JSON File Example
void readJSONFile(const char *filename) { // Open the JSON file for reading FILE *file = fopen(filename, "r"); if (!file) { fprintf(stderr, "Error opening file: %s\n", filename); return; } // Get the file size fseek(file, 0, SEEK_END); long fileSize = ftell(file); fseek(file, 0, SEEK_SET); // Read the entire file into a buffer char *buffer = (char *)malloc(fileSize + 1); fread(buffer, 1, fileSize, file); buffer[fileSize] = '\0'; // Null-terminate the string // Close the file fclose(file); // Parse the JSON data cJSON *json = cJSON_Parse(buffer); // Check if parsing was successful if (json == NULL) { const char *error_ptr = cJSON_GetErrorPtr(); if (error_ptr != NULL) { fprintf(stderr, "Error before: %s\n", error_ptr); } cJSON_Delete(json); free(buffer); return; } // Process the JSON data (modify as needed) // ... // Clean up cJSON_Delete(json); free(buffer); } int main() { const char *filename = "example.json"; readJSONFile(filename); return 0; }
Write JSON to File Example
Next, let’s see an example of how to write JSON data to a file:
void write_json_to_file(const char *filename) { cJSON *json = cJSON_CreateObject(); cJSON_AddStringToObject(json, "hello", "world"); FILE *file = fopen(filename, "w"); if (file == NULL) { fprintf(stderr, "Could not open %s for writing\n", filename); cJSON_Delete(json); return; } char *json_string = cJSON_Print(json); fprintf(file, "%s", json_string); fclose(file); cJSON_Delete(json); free(json_string); } // Example usage write_json_to_file("output.json");
Output:
{ "hello": "world" }
The write_json_to_file
function creates a new JSON object, adds a “hello” key with the value “world”, and writes the JSON string to a file. Note the importance of freeing the allocated string using free
after writing to the file.
Print JSON Object Example
Now, let’s print a JSON object:
void print_json_object(const char *json_string) { cJSON *json = cJSON_Parse(json_string); char *formatted_json = cJSON_Print(json); printf("%s\n", formatted_json); cJSON_Delete(json); free(formatted_json); } // Example usage const char *my_json = "{\"greeting\":\"hello\"}"; print_json_object(my_json);
Output:
{ "greeting": "hello" }
In this print_json_object
function, we parse a JSON string and then print it in a nicely formatted way using cJSON_Print
before freeing the allocated string.
Parse JSON Array Example
To parse a JSON array, follow this example:
void parse_json_array(const char *json_string) { cJSON *json = cJSON_Parse(json_string); cJSON *numbers = cJSON_GetObjectItemCaseSensitive(json, "numbers"); cJSON *number = NULL; cJSON_ArrayForEach(number, numbers) { if (cJSON_IsNumber(number)) { printf("Number: %d\n", number->valueint); } } cJSON_Delete(json); } // Example usage const char *my_json = "{\"numbers\":[1, 2, 3, 4, 5]}"; parse_json_array(my_json);
Output:
Number: 1 Number: 2 Number: 3 Number: 4 Number: 5
This function, parse_json_array
, specifically handles an array of numbers. We iterate over each element and print its value.
Array of Objects Example
To handle an array of objects, consider this cJSON example:
void parse_array_of_objects(const char *json_string) { cJSON *json = cJSON_Parse(json_string); cJSON *users = cJSON_GetObjectItemCaseSensitive(json, "users"); cJSON *user = NULL; cJSON_ArrayForEach(user, users) { cJSON *name = cJSON_GetObjectItemCaseSensitive(user, "name"); cJSON *age = cJSON_GetObjectItemCaseSensitive(user, "age"); if (cJSON_IsString(name) && cJSON_IsNumber(age)) { printf("Name: %s, Age: %d\n", name->valuestring, age->valueint); } } cJSON_Delete(json); } // Example usage const char *my_json = "{\"users\":[{\"name\":\"John\", \"age\":30}, {\"name\":\"Jane\", \"age\":25}]}"; parse_array_of_objects(my_json);
Output:
Name: John, Age: 30 Name: Jane, Age: 25
In the parse_array_of_objects
function, we are accessing an array where each element is an object with its own set of keys. We print out each object’s name and age.
Citations and References
Conclusive Summary
In this tutorial, we explored various examples using the cJSON library in C. We covered how to parse JSON objects and arrays, write JSON data to files, and print JSON in a human-readable format. By following these examples, developers can manipulate JSON data effectively for application configurations, data exchange with web services, and more. The clarity and simplicity of the cJSON library make it an excellent choice for handling JSON data in C.