The Wayback Machine - https://web.archive.org/web/20241109194328/https://www.geeksforgeeks.org/cjson-json-file-write-read-modify-in-c/
Open In App

cJSON – JSON File Write/Read/Modify in C

Last Updated : 15 May, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy to read and write for humans and machines alike. JSON is widely used for data exchange between applications and web services. In this article, we will discuss how to read and write JSON data in the C programming language.

JSON in C

JSON in C can be handled using the cJSON library, which is an open-source library available under the MIT License. It provides a simple and easy-to-use API for parsing, creating, and manipulating JSON data. The cJSON library is written in C and has no external dependencies, making it easy to integrate into C programs.

Writing JSON Data

To write JSON data in C, we need to create a cJSON object and convert it to a JSON string using the cJSON library. Here is an example code snippet to write JSON data to a file:

C




#include <stdio.h>
#include <cjson/cJSON.h>
  
int main() {
   // create a cJSON object
   cJSON *json = cJSON_CreateObject();
   cJSON_AddStringToObject(json, "name", "John Doe");
   cJSON_AddNumberToObject(json, "age", 30);
   cJSON_AddStringToObject(json, "email", "john.doe@example.com");
  
   // convert the cJSON object to a JSON string
   char *json_str = cJSON_Print(json);
  
   // write the JSON string to a file
   FILE *fp = fopen("data.json", "w");
   if (fp == NULL) {
       printf("Error: Unable to open the file.\n");
       return 1;
   }
   printf("%s\n", json_str);
   fputs(json_str, fp);
   fclose
   // free the JSON string and cJSON object
   cJSON_free(json_str);
   cJSON_Delete(json);
   return 0;
}


Output: 

Console Output

{
    "name": "John Doe",
    "age": 30,
    "email": "john.doe@example.com"
}

Generated JSON file

Generated JSON file

Generated JSON file

Code Explanation:

In this example, we first create a cJSON object using the `cJSON_CreateObject()` function. We then add key-value pairs to the object using the `cJSON_AddStringToObject()` and `cJSON_AddNumberToObject()` functions. We then convert the cJSON object to a JSON string using the `cJSON_Print()` function, which returns a dynamically allocated string that needs to be freed using the `cJSON_free()` function. We then write the JSON string to a file using the `fputs()` function. Finally, we delete the cJSON object using the `cJSON_Delete()` function.

Note 1: In the above program, the output is the JSON data written to a file named “data.json”. The contents of the file are the same as the JSON data printed to the console.

Note 2: The formatting of the JSON data in the output may differ depending on the operating system and text editor used. However, the contents of the JSON data will remain the same.

Reading JSON Data

To read JSON data in C, we need to parse the JSON string using the cJSON library. Here is an example code snippet to read JSON data from a file:

C




#include <stdio.h>
#include <cjson/cJSON.h>
  
int main() {
    // open the file
    FILE *fp = fopen("data.json", "r");
    if (fp == NULL) {
        printf("Error: Unable to open the file.\n");
        return 1;
    }
  
    // read the file contents into a string
    char buffer[1024];
    int len = fread(buffer, 1, sizeof(buffer), fp);
    fclose(fp);
  
    // parse the JSON data
    cJSON *json = cJSON_Parse(buffer);
    if (json == NULL) {
        const char *error_ptr = cJSON_GetErrorPtr();
        if (error_ptr != NULL) {
            printf("Error: %s\n", error_ptr);
        }
        cJSON_Delete(json);
        return 1;
    }
  
    // access the JSON data
    cJSON *name = cJSON_GetObjectItemCaseSensitive(json, "name");
    if (cJSON_IsString(name) && (name->valuestring != NULL)) {
        printf("Name: %s\n", name->valuestring);
    }
  
    // delete the JSON object
    cJSON_Delete(json);
    return 0;
}


Input: (JSON File)

JSON File for input

JSON File for input

Output: 

Name: John Doe

In this example, we first open the JSON file using the fopen() function and check if it is successful. Then we read the file contents into a buffer using the fread() function. We close the file using the fclose() function. We then parse the JSON data using the cJSON_Parse() function, which returns a pointer to a cJSON object. If the parsing fails, we print the error message using the cJSON_GetErrorPtr() function. We then access the JSON data using the cJSON_GetObjectItemCaseSensitive() function, which returns a pointer to a cJSON object corresponding to the given key. Finally, we delete the cJSON object using the cJSON_Delete() function.

Modifying Existing JSON file Data

Certainly! To modify an existing JSON file, we can use the cJSON library’s functions to read the file into a cJSON object, modify the object, and then write the modified object back to the file. Here’s an example program that demonstrates how to modify a JSON file using the cJSON library in C:

C




#include <stdio.h>
#include <cjson/cJSON.h>
  
int main() {
    // open the JSON file
    FILE *fp = fopen("data.json", "r");
    if (fp == NULL) {
        printf("Error: Unable to open the file.\n");
        return 1;
    }
  
    // read the file contents into a string
    char buffer[1024];
    int len = fread(buffer, 1, sizeof(buffer), fp);
    fclose(fp);
  
    // parse the JSON data
    cJSON *json = cJSON_Parse(buffer);
    if (json == NULL) {
        const char *error_ptr = cJSON_GetErrorPtr();
        if (error_ptr != NULL) {
            printf("Error: %s\n", error_ptr);
        }
        cJSON_Delete(json);
        return 1;
    }
  
    // modify the JSON data
    cJSON_ReplaceItemInObjectCaseSensitive(json, "name", cJSON_CreateString("Jane Doe"));
    cJSON_AddNumberToObject(json, "age", 32);
    cJSON_AddStringToObject(json, "phone", "555-555-5555");
  
    // convert the cJSON object to a JSON string
    char *json_str = cJSON_Print(json);
  
    // write the JSON string to the file
    fp = fopen("data.json", "w");
    if (fp == NULL) {
        printf("Error: Unable to open the file.\n");
        return 1;
    }
    printf("%s\n", json_str);
    fputs(json_str, fp);
    fclose(fp);
  
    // free the JSON string and cJSON object
    cJSON_free(json_str);
    cJSON_Delete(json);
  
    return 0;
}


In this example program, we first open the JSON file, read its contents into a string, and parse the JSON data using the cJSON_Parse() function. We then modify the JSON data by replacing the value of the “name” key with a new string, adding a new key-value pair for “phone”, and changing the value of the “age” key to 32. We then convert the cJSON object back to a JSON string using the cJSON_Print() function, write the JSON string to the file using the fputs() function, and free the cJSON object and JSON string. After running this program, the “data.json” file should now contain the modified JSON data.

Input: (JSON File)

JSON file for input

JSON file for input

Output:

Console

{
   "name": "Jane Doe",
   "age": 32,
   "email": "john.doe@example.com",
   "phone": "555-555-5555"
}

Modified JSON File

Modified JSON file

Modified JSON file

Note: In this example, we used the cJSON_ReplaceItemInObjectCaseSensitive() function to replace the value of the “name” key, which is case-sensitive. If the key is not case-sensitive, we can use the cJSON_ReplaceItemInObject() function instead. Also, we can modify the JSON data in any way we want using the cJSON library’s various functions.

Conclusion

In this article, we discussed how to read and write JSON data in C using the cJSON library. The cJSON library provides a simple and easy-to-use API for handling JSON data in C. By using this library, we can easily integrate JSON data into our C programs and exchange data with other applications and web services.



Similar Reads

Convert JSON file into CSV file and displaying the data using Node.js
There are so many ways to store data for better understanding for individual purposes, in few cases, JSON files will be more suitable in few cases, CSV files, and there are also lots of other types as well like XML, etc. In this article, we will convert the JSON file data into CSV file data and also display that through Node.js. JSON stands for Jav
3 min read
How to parse JSON object using JSON.stringify() in JavaScript ?
In this article, we will see how to parse a JSON object using the JSON.stringify function. The JSON.stringify() function is used for parsing JSON objects or converting them to strings, in both JavaScript and jQuery. We only need to pass the object as an argument to JSON.stringify() function. Syntax: JSON.stringify(object, replacer, space); Paramete
2 min read
What is difference between JSON.parse() and JSON.stringify() Methods in JavaScript ?
JSON.parse() converts JSON strings to JavaScript objects, while JSON.stringify() converts JavaScript objects to JSON strings. JavaScript utilizes JSON for data interchange between servers and web pages. These methods enable easy data manipulation and transport in web development. JSON.parse() MethodJSON.parse() converts a JSON string to a JavaScrip
2 min read
How to use cURL to Get JSON Data and Decode JSON Data in PHP ?
In this article, we are going to see how to use cURL to Get JSON data and Decode JSON data in PHP. cURL: It stands for Client URL.It is a command line tool for sending and getting files using URL syntax.cURL allows communicating with other servers using HTTP, FTP, Telnet, and more.Approach: We are going to fetch JSON data from one of free website,
2 min read
How to generate Json File in PHP ?
In this article, we are going to generate a JSON file in PHP by using an array. JSON stands for JavaScript object notation, which is used for storing and exchanging data. JSON is text, written with JavaScript object notation. Structure: {"data":[ { "sub_data1":"value1", "sub_data2":"value2","sub_data_n":"value n" }, { "sub_data2":"value2","sub_data
3 min read
How to work with Node.js and JSON file ?
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. With node.js as backend, the developer can maintain a single codebase for an entire application in javaScript.JSON on the other hand, stands for JavaScript Object Notation. It is a lightweight format for storing and exchanging data.Creating a Script: Node.js scripts are created
4 min read
How to Convert CSV to JSON file and vice-versa in JavaScript ?
CSV files are a common file format used to store data in a table-like manner. They can be particularly useful when a user intends to download structured information in a way that they can easily open and read on their local machine. CSV files are ideal for this because of their portability and universality. In this article, we will explain how to c
3 min read
How to Convert JSON file into CSV in PHP ?
In this article, we are going to see how to convert JSON data into a CSV file using PHP. JSON (JavaScript Object Notation) is a dictionary-like notation that can be used to structuring data. It is stored with the extension .json, for example - geeksforgeeks.json On the other hand, CSV (or Comma Separated Value) files represent data in a tabular for
2 min read
Which functions are used to encode and decode JSON file in PHP ?
JSON stands for JavaScript Object Notation. Like XML, it is a text-based format for the exchange of data which is easier to read and write and it is lighter than other formats. JSON is based on two basic structures namely Objects and Arrays. Parsing JSON data in PHP: There are built-in functions in PHP for both encoding and decoding JSON data. Thes
2 min read
What is the purpose of using tsconfig.json file ?
tsconfig.json file is a file of JSON format which allows us to point the root level files and different compiler options to setup that require to compile a TypeScript based projects. The existence of this file in a project specifies that the given directory is the TypeScript project folder root. The tsconfig.json file mainly consists of the informa
2 min read
How to load a JSON object from a file with ajax?
Loading a JSON object from a file using AJAX involves leveraging XMLHttpRequest (XHR) or Fetch API to request data from a server-side file asynchronously. By specifying the file's URL and handling the response appropriately, developers can seamlessly integrate JSON data into their web applications. This method enables dynamic loading of data withou
3 min read
How to Upload File and JSON Data in Postman?
Postman is a very famous API development tool used to test APIs. Postman simplifies the process of the API lifecycle to create and test better APIs. Now, while we are working with APIs sometimes we need to send JSON as data or upload a file through API. There may be a scenario where we have to do both tasks in a single API. Prerequisites:Express Js
4 min read
How to open JSON file ?
In this article, we will open the JSON file using JavaScript.  JSON stands for JavaScript Object Notation. It is basically a format for structuring data. The JSON format is a text-based format to represent the data in form of a JavaScript object. Approach: Create a JSON file, add data in that JSON file.Using JavaScript fetch the created JSON file u
2 min read
How to Fix "Does Not Appear to Have a File Named config.json"?
When working with certain applications, especially those involving configuration files, you might encounter an error stating, "Does not appear to have a file named config.json." This issue typically arises when the application expects a configuration file (config.json) in a specific location, but it is either missing or incorrectly named. Below are
4 min read
How to open json file ?
A JSON (JavaScript Object Notation) file is a standard format used to store and exchange data. Initially, JSON was primarily used for data transfer between web applications and servers, but its usage has expanded significantly. Today, JSON files are used for various purposes, including data backups and configuration files. JSON files have the .json
3 min read
How To Convert CSV to JSON file Having Comma Separated Values In NodeJS?
To convert a CSV file into a JSON file in Node.js with comma-separated values, follow a structured approach that utilizes the fs module to read the file and process the data manually. Here's how you can achieve the solution ApproachRead the CSV file using the default fs npm package.Convert the data to String and split it in an array.Generate a head
3 min read
How to fetch data from a local JSON file in React Native ?
Fetching JSON (JavaScript Object Notation) data in React Native from Local (E.g. IOS/Android storage) is different from fetching JSON data from a server (using Fetch or Axios). It requires Storage permission for APP and a Library to provide Native filesystem access. Implementation: Now let’s start with the implementation: Step 1: Open your terminal
4 min read
Read JSON File Using JavaScript
To read a JSON file using JavaScript, you have several options depending on the environment you're working in. In JavaScript, reading a JSON file involves converting the JSON content into a JavaScript object or array for easy manipulation. This can be done in the browser with fetch() or in Node.js using fs.readFile() or require(). After fetching, u
4 min read
How to Update Data in JSON File using Node?
To update data in JSON file using Node.js, we can use the require module to directly import the JSON file. Updating data in a JSON file involves reading the file and then making the necessary changes to the JSON object and writing the updated data back to the file. Table of Content Using require() MethodUsing File System ModuleUsing require() Metho
4 min read
C program to copy contents of one file to another file
[GFGTABS] C #include <stdio.h> #include <stdlib.h> // For exit() int main() { FILE *fptr1, *fptr2; char filename[100]; int c; printf("Enter the filename to open for reading: "); scanf("%s", filename); // Open one file for reading fptr1 = fopen(filename, "r"); if (fptr1 == NULL) { printf("Cannot open fi
1 min read
JavaScript | JSON HTML
HTML table: In the HTML, tables are defined by <table> tag, table's header are defined by <th> tag and by default table's header are placed in center and it is bold and row of the table is defined by <tr> and the data or information of the row is defined by <td> tag. Below code shows the demonstration of the HTML table: Code
3 min read
Convert Java Object to Json String using Jackson API
JSON stands for JavaScript Object Notation. It's a standard text-based format that shows structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications. JSON is highly recommended to transmit data between a server and web application. In order to convert a Java object into JSON, the following two me
3 min read
How to receive JSON POST with PHP ?
In this article, we will see how to retrieve the JSON POST with PHP, & will also see their implementation through the examples. First, we will look for the below 3 features: php://input: This is a read-only stream that allows us to read raw data from the request body. It returns all the raw data after the HTTP headers of the request, regardless
2 min read
Interesting facts about JSON
JSON or JavaScript Object Notation is a lightweight format for transporting and storing data. JSON is used when data is transferred from a server to a web page. This language is also characterized as weakly typed, prototype-based, dynamic, and multi-paradigm. Here are some interesting facts about JSON: JSON was derived from JavaScript but by 2017 m
2 min read
Convert Java Object to Json String using GSON
JSON Stand for JavaScript Object Notation. It's a standard text-based format which shows structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications. JSON is highly recommended to transmit data between a server and web application. To convert a Java object into JSON, the following methods can be
2 min read
Convert Json String to Java Object Using GSON
Pre-requisite: Convert Java Object to Json String Using GSONJSON Stand for JavaScript Object Notation. It's a standard text-based format which shows structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications. JSON is highly recommended to transmit data between a server and web application. To co
3 min read
JavaScript | Remove a JSON attribute
In this article, we will see how to remove a JSON attribute from the JSON object. To do this, there are few of the mostly used techniques discussed. First delete property needs to be discussed. Delete property to Remove a JSON Attribute This keyword deletes a property from an object: This keyword deletes both the value of the property and the prope
2 min read
JavaScript | Add new attribute to JSON object
The task is to add a JSON attribute to the JSON object. To do so, Here are a few of the most used techniques discussed.Example 1: This example adds a prop_11 attribute to the myObj object via var key. C/C++ Code <!DOCTYPE HTML> <html> <head> <title> JavaScript | Add new attribute to JSON object. </title> </head>
2 min read
How to send a JSON object to a server using Javascript?
JavaScript Object Notation (JSON). It is a lightweight data transferring format. It is very easy to understand by human as well as machine. It is commonly used to send data from or to server. Nowadays it is widely used in API integration because of its advantages and simplicity.In this example we are going to use AJAX (Asynchronous JavaScript And X
2 min read
How to swap key and value of JSON element using JavaScript ?
In this article, we will swap the key and value of JSON elements using JavaScript. Given a JSON object and the task is to swap the JSON object key with values and vice-versa with the help of JavaScript. Below are the following approaches: Using for loopUsing Object.keys() and ForEach() MethodUsing Object.entries() and map() MethodApproach 1: Using
2 min read
Article Tags :
three90RightbarBannerImg