Creating a JSON document in C requires a library, since C's standard library does not include JSON tools

C does not have built-in JSON support, so you need to choose a library that handles JSON creation and formatting. The most widely used options are cJSON (lightweight and beginner-friendly), jansson (more features, better for complex structures), and json-c (mature and stable). Each library works differently, but the basic process is the same: create objects and arrays, add data to them, convert to a string, and write to a file or send over a network.

This guide covers how to set up a library, build a JSON structure, and output it as text. The examples use cJSON because it has the simplest syntax for beginners, but the concepts apply to any JSON library in C.

Key Takeaways

  • You must download and link a JSON library — cJSON, jansson, or json-c are the most common choices for C projects.
  • Create objects with cJSON_CreateObject(), add key-value pairs with cJSON_AddStringToObject() or similar functions, and nest structures as needed.
  • Convert your structure to a string with cJSON_Print() or cJSON_PrintUnformatted(), then write that string to a file or send it elsewhere.
  • Always free memory with cJSON_Delete() when you finish, or your program will leak memory.
  • Test your output by opening the JSON file in a text editor or validator to confirm the structure is correct.

Setting up cJSON in your project

Download cJSON from its GitHub repository (search "cJSON GitHub"). You will find two files: cJSON.h and cJSON.c. Copy both into your project folder alongside your own C files.

In your C program, include the header at the top:

#include "cJSON.h"

When you compile, include cJSON.c in the compilation command. For example, if your program is called main.c, compile it like this:

gcc main.c cJSON.c -o myprogram

If you use an IDE like Visual Studio or Code::Blocks, add cJSON.c to your project file list instead of typing it on the command line. The library will then compile alongside your code.

Building a simple JSON object

Start by creating an empty object with cJSON_CreateObject(). This gives you a container to hold key-value pairs.

cJSON *root = cJSON_CreateObject(); cJSON_AddStringToObject(root, "name", "Alice"); cJSON_AddNumberToObject(root, "age", 30); cJSON_AddBoolToObject(root, "active", 1);

The first argument to each Add function is the object you created. The second is the key (the name of the field), and the third is the value. Use cJSON_AddStringToObject() for text, cJSON_AddNumberToObject() for integers or decimals, and cJSON_AddBoolToObject() for true or false.

When you print this object, it will look like:

{"name":"Alice","age":30,"active":true}

Adding arrays and nested objects

JSON often contains arrays (lists of values) and objects nested inside other objects. Create an array with cJSON_CreateArray() and add it to your root object with cJSON_AddItemToObject().

cJSON *hobbies = cJSON_CreateArray(); cJSON_AddItemToArray(hobbies, cJSON_CreateString("reading")); cJSON_AddItemToArray(hobbies, cJSON_CreateString("coding")); cJSON_AddItemToObject(root, "hobbies", hobbies);

To add a nested object, create a new object and add it the same way:

cJSON *address = cJSON_CreateObject(); cJSON_AddStringToObject(address, "city", "Portland"); cJSON_AddStringToObject(address, "state", "OR"); cJSON_AddItemToObject(root, "address", address);

Your JSON now contains an array and a nested object. The structure looks like:

{"name":"Alice","age":30,"active":true,"hobbies":["reading","coding"],"address":{"city":"Portland","state":"OR"}}

Converting to a string and writing to a file

Once your structure is complete, convert it to a formatted string with cJSON_Print(). This adds line breaks and indentation to make it readable.

char *json_string = cJSON_Print(root);

Write this string to a file using standard C file functions:

FILE *file = fopen("output.json", "w"); fprintf(file, "%s", json_string); fclose(file);

If you do not need the formatted version (for example, if you are sending it over a network and want to save space), use cJSON_PrintUnformatted() instead. It produces the same JSON without extra whitespace.

After writing, free the string and the root object to avoid memory leaks:

free(json_string); cJSON_Delete(root);

Choosing between cJSON, jansson, and json-c

cJSON is the easiest to learn and requires no installation beyond copying two files into your project. It handles most common JSON tasks and produces clean, readable code. Use cJSON if you are new to JSON in C or building a small project.

jansson is more powerful and includes tools for parsing JSON (reading it back in), validating structure, and handling errors in detail. It requires installation via a package manager or building from source, which takes more setup time. Use jansson if your project reads JSON files or needs robust error handling.

json-c is the oldest and most stable of the three. It is widely used in large projects and available in most Linux package managers. It has more functions than cJSON but a steeper learning curve. Use json-c if you are working on an established project that already uses it or if you need maximum compatibility across systems.

For most beginners, cJSON is the right choice. It compiles quickly, has clear function names, and does not require system-level installation.

Common mistakes and how to avoid them

Forgetting to free memory is the most common error. Every object and array you create with cJSON_Create must be deleted with cJSON_Delete() when you are done. If you add an item to an object with cJSON_AddItemToObject(), calling cJSON_Delete() on the parent object will also delete the child, so you only need to delete the root.

Passing the wrong data type causes silent failures. If you use cJSON_AddNumberToObject() with a string variable, the library will not warn you — it will just store garbage. Always match the function to your data type: strings get AddString, numbers get AddNumber, booleans get AddBool.

Not checking the output file is another trap. Always open the JSON file in a text editor after your program runs to confirm it is valid. Paste it into a JSON validator (search "JSON validator online") to catch structure errors that your code might not catch.

Frequently Asked Questions

Can I read a JSON file that already exists?

cJSON can parse JSON strings with cJSON_Parse(), but you have to read the file into memory first using standard C file functions. jansson and json-c have built-in file reading functions that are more convenient. If you need to read JSON regularly, jansson is worth the extra setup time.

What if I need to add a null value to my JSON?

Use cJSON_AddNullToObject(root, "key"). This creates a key with no value, which is valid JSON and useful when a field should exist but has no data.

How do I add a decimal number instead of an integer?

Use cJSON_AddNumberToObject() with a decimal value, like cJSON_AddNumberToObject(root, "price", 19.99). The function handles both integers and decimals automatically.

Can I modify a JSON object after I create it?

Yes. Use cJSON_GetObjectItem(root, "key") to find an existing field, then modify its value directly. For example, root->child->valueint = 25 changes a number field. This is useful if you build a structure once and update it multiple times before writing to a file.

What happens if my JSON structure is very large?

cJSON loads the entire structure into memory, which can be slow for files over a few megabytes. For very large JSON documents, jansson or json-c may perform better, or consider streaming the output directly to a file instead of building the whole structure first.