The Wayback Machine - https://web.archive.org/web/20241010194708/https://www.geeksforgeeks.org/rapidjson-file-read-write-in-cpp/
Open In App

RapidJSON – File Read/Write in C++

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

RapidJSON is a C++ library for parsing and generating JSON (JavaScript Object Notation) data.  It is designed for high performance and can handle very large JSON documents. RapidJSON supports both reading and writing JSON data, as well as validation and manipulation of JSON objects. It also includes support for parsing and generating JSON in a streaming fashion, which can be useful for working with large JSON data sets. To read a JSON file using RapidJSON, you can use the rapidjson::Document class. The Document class provides a high-level API for parsing and manipulating JSON data, and it can be used to read JSON data from a file. Here is an example of how to read a JSON file using Document: Here are examples of how to read a JSON file using RapidJSON.

Examples

Example 1:

C++




#include "rapidjson/document.h"
#include <fstream>
#include <iostream>
  
using namespace std;
using namespace rapidjson;
  
int main()
{
    // Open the file
    ifstream file("example.json");
  
    // Read the entire file into a string
    string json((istreambuf_iterator<char>(file)),
                istreambuf_iterator<char>());
  
    // Create a Document object 
      // to hold the JSON data
    Document doc;
  
    // Parse the JSON data
    doc.Parse(json.c_str());
  
    // Check for parse errors
    if (doc.HasParseError()) {
        cerr << "Error parsing JSON: "
             << doc.GetParseError() << endl;
        return 1;
    }
  
    // Now you can use the Document object to access the
    // JSON data
    return 0;
}


Input: example.json (existing JSON file)

 

Output: none (the code only reads the JSON data from the file and stores it in a Document object)

In this example, the ifstream class is used to open the file “example.json” and read its contents into a string. The doc.Parse(json.c_str()) function is then used to parse the JSON data in the string. RapidJSON provides the ParseErrorCode enumeration to indicate the type of error that occurred during parsing. You can use this enumeration to handle errors in your code. For example, you can use the HasParseError() method to check if an error occurred during parsing and the GetParseError() method to get the error code. If the parse is successful, you can then use the Document object to access the JSON data.

C++




if (doc.HasParseError()) {
    switch (doc.GetParseError()) {
    case kParseErrorNone:
        cout << "No error" << std::endl;
        break;
    case kParseErrorDocumentEmpty:
        cout << "Error: Document is empty" << std::endl;
        break;
    case kParseErrorDocumentRootNotSingular:
        cout << "Error: Document root is not singular"
             << std::endl;
        break;
        // ...
    }
}


Example 2: How to read a JSON file using RapidJSON

C++




#include "rapidjson/document.h"
#include "rapidjson/filereadstream.h"
#include <iostream>
  
int main()
{
    // Open the file for reading
    FILE* fp = fopen("data.json", "r");
  
    // Use a FileReadStream to
      // read the data from the file
    char readBuffer[65536];
    rapidjson::FileReadStream is(fp, readBuffer,
                                 sizeof(readBuffer));
  
    // Parse the JSON data 
      // using a Document object
    rapidjson::Document d;
    d.ParseStream(is);
  
    // Close the file
    fclose(fp);
  
    // Access the data in the JSON document
    std::cout << d["name"].GetString() << std::endl;
    std::cout << d["age"].GetInt() << std::endl;
  
    return 0;
}


Input: data.json (existing JSON file)

{
  "name": "Geek",
  "age": 30
}

Output:

Geek
30

This code first opens a file called “data.json” for reading. It then uses a FileReadStream to read the data from the file into a buffer. The data is then parsed using a Document object, which provides access to the data in the JSON document. The code then closes the file and accesses the “name” and “age” fields in the JSON document, printing them out.

To write a JSON file using RapidJSON, you can use the rapidjson::Document class along with the rapidjson::FileWriteStream class and rapidjson::Writer. Here is an example of how to write a JSON object to a file. Here is an example of how to use RapidJSON to write a JSON file in C++:

C++




#include "rapidjson/document.h"
#include "rapidjson/filewritestream.h"
#include "rapidjson/writer.h"
#include <fstream>
#include <iostream>
  
using namespace rapidjson;
  
int main()
{
    // Create the JSON document
    Document d;
    d.SetObject();
  
    // Add data to the JSON document
    d.AddMember("name", "Geek", d.GetAllocator());
    d.AddMember("age", 30, d.GetAllocator());
  
    // Open the output file
    std::ofstream file("example.json");
  
    // Write the JSON data to the file
    FileWriteStream os(file, buffer, sizeof(buffer));
    Writer<FileWriteStream> writer(os);
    d.Accept(writer);
  
    return 0;
}


Input: none (the code creates the JSON data from scratch)

Output: example.json (generated JSON file)

 

This code creates a JSON document object using the RapidJSON library, and then adds a “name” field with the value “Geek” and an “age” field with the value 30 to the document. It then opens an output file called “example.json” using a std::ofstream object. Finally, it writes the JSON document to the output file using the FileWriteStream and Writer classes from the RapidJSON library. The resulting output file will be a JSON file with the name “example.json” with the content {“name”: “Geek”,”age”: 30}. Here is an example of how to use RapidJSON to read and write a JSON file in C++:

C++




#include "rapidjson/document.h"
#include "rapidjson/filereadstream.h"
#include "rapidjson/filewritestream.h"
#include "rapidjson/writer.h"
  
using namespace rapidjson;
  
int main()
{
    // Read JSON file
    FILE* fp
        = fopen("data.json", "rb"); // non-Windows use "r"
    char readBuffer[65536];
    FileReadStream is(fp, readBuffer, sizeof(readBuffer));
    Document d;
    d.ParseStream(is);
    fclose(fp);
  
    // Modify the JSON data
    Value& s = d["name"];
    s.SetString("geek geeks", d.GetAllocator());
  
    // Write JSON file
    FILE* fp2 = fopen("data_modified.json",
                      "wb"); // non-Windows use "w"
    char writeBuffer[65536];
    FileWriteStream os(fp2, writeBuffer,
                       sizeof(writeBuffer));
    Writer<FileWriteStream> writer(os);
    d.Accept(writer);
    fclose(fp2);
  
    return 0;
}


Input: data.json (original JSON file)

 

Output: data_modified.json (modified JSON file)

 

In this example, we first read a JSON file named “data.json” using the FileReadStream class. The data is then stored in a rapidjson::Document object, which can be used to access and modify the JSON data.

Once the data has been modified, we use the FileWriteStream class to write the modified data to a new JSON file named “data_modified.json”. The Writer class is used to write the JSON data to the output stream in a properly formatted way. It’s worth noting that the code uses FILE* and fopen/fclose for reading and writing the files. This is the traditional C way of doing file operations, but C++ also provides more modern alternatives like ifstream and ofstream.

In the above example, The variable s is assigned to the value of the “name” key in the JSON document, and its value is modified to “geek geeks” using the SetString() method. It is also important to note that RapidJSON uses an allocator to manage memory while parsing and serializing JSON data, so it should be passed when needed as in s.SetString(“geek geeks”, d.GetAllocator());



Similar Reads

How to Read and Parse Json File with RapidJson?
RapidJSON is a high-performance JSON library for C++. It provides a fast and easy-to-use interface for parsing and generating JSON. It is small but complete. It supports both SAX and DOM style API. Also, it is self-contained and header-only. It does not depend on external libraries such as BOOST. It even does not depend on STL. Here is an example o
5 min read
How to Parse an Array of Objects in C++ Using RapidJson?
RapidJSON is an open-source C++ library for parsing and serializing JSON (JavaScript Object Notation) data. It is designed to be fast and efficient, with a focus on simplicity and ease of use. It is widely used in a variety of applications and is known for its fast performance and low memory overhead. It is a popular choice for parsing and serializ
4 min read
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
Difference Between C++ Text File and Binary File
A text file is the one in which data is stored in the form of ASCII characters and is normally used for storing a stream of characters. Text files are organized around lines, each of which ends with a newline character ('\n'). The source code files are themselves text files. A binary file is the one in which data is stored in the file in the same w
4 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
Copy File To Vector in C++ STL
Prerequisite: Vectors in C++ STLFile Handling in C++ The C++ Standard Template Library (STL) provides several useful container classes that can be used to store and manipulate data. One of the most commonly used container classes is the vector. In this article, we will discuss how to copy the contents of a file into a vector using C++ STL. Approach
2 min read
clocale header file in C++
clocale: This header file contains declaration of a set of functions and a type for internationalization support tasks. It supports date format or country specific currency symbols. For example, date/time formatting, monetary formatting and many more. Methods in clocale header: localeconv(): This function returns an object which represents numeric
2 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
ATM using file handling in C++
In this article, the task is to implement an ATM with functions like add, delete, search, and update users using file handling in C++. File handling: File handling is used to store the output of a program in a file.In C++, files use three classes fstream, ifstream, ofstream available in fstream header file for file handling. Some Important Instruct
6 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
Reading Lines by Lines From a File to a Vector in C++ STL
Prerequisites: STL in C++Vector in C++File handling in C++ The Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and functions such as lists, stacks, arrays, etc. It is a library of container classes, algorithms, and iterators. Vector in C++ STL Vectors are the same as dynamic arrays with
2 min read
cJSON - JSON File Write/Read/Modify in C
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
6 min read
File System Library in C++17
In this article, we will learn about the File System library in C++17 and with examples. <filesystem> header was added in C++17 and introduces a set of classes, functions, and types that simplify file system operations. In simple words, we can say that the filesystem library provides tools that help us to simplify working with files and direc
6 min read
C++ program to print unique words in a file
Write a function that takes a file name as argument and prints all unique words in it. We strongly recommend you to minimize your browser and try this yourself first The idea is to use map in STL to keep track of words already occurred. C/C++ Code // C++ program to print unique words in a string #include <bits/stdc++.h> using namespace std; /
2 min read
Implement your own tail (Read last n lines of a huge file)
Given a huge file having dynamic data, write a program to read last n lines from the file at any point without reading the entire file. The problem is similar to tail command in linux which displays the last few lines of a file. It is mostly used for viewing log file updates as these updates are appended to the log files. Source : Microsoft Intervi
4 min read
Four File Handling Hacks which every C/C++ Programmer should know
We will discuss about four file hacks listed as below- Rename - Rename a file using C/C++Remove – Remove a file using C/C++File Size - Get the file size using C/C++Check existence – Check whether a file exists or not in C/C++ C/C++ Code // C++ Program to demonstrate the // four file hacks every C/C++ must know // Note that we are assuming that the
3 min read
lseek() in C/C++ to read the alternate nth byte and write it in another file
From a given file (e.g. input.txt) read the alternate nth byte and write it on another file with the help of “lseek”. lseek (C System Call): lseek is a system call that is used to change the location of the read/write pointer of a file descriptor. The location can be set either in absolute or relative terms. Function Definition off_t lseek(int fild
2 min read
Print "Hello World" in C/C++ without using any header file
Write a C/C++ program that prints Hello World without including any header file. Conceptually it's seems impractical to write a C/C++ program that print Hello World without using a header file of "stdio.h". Since the declaration of printf() function contains in the "stdio.h" header file. But we can easily achieve this by taking the advantage of C p
2 min read
Understanding ShellExecute function and it's application to open a list of URLs present in a file using C++ code
Given a URL as a string open it using a C++ code in Microsoft Windows OS. Example: Input : https://www.geeksforgeeks.org/ Output : The site opened in your browser. // C++ program to open a URL in browser. // This program is written on for Microsoft // Windows OS #include <bits/stdc++.h> #include <windows.h> using namespace std; int main
5 min read
Read/Write Class Objects from/to File in C++
Given a file "Input.txt" in which every line has values same as instance variables of a class. Read the values into the class's object and do necessary operations.Theory : The data transfer is usually done using '>>' and <<' operators. But if you have a class with 4 data members and want to write all 4 data members from its object direc
3 min read
Find sum of integers in a file which contains any characters
You are given a text file which contains any type of characters. You have to find the sum of integer values. Examples: Input : text.txt Let contents of test.txt be : :-,,$%^5313&^*1)(*( 464sz29>>///11!!! (*HB%$#)(*0900 Output : 6727 Input : text1.txt Let contents of test.txt be : 234***3r3r() ()(0)34 Output : 274 Steps : 1. To open the fi
2 min read
Set Position with seekg() in C++ File Handling
seekg() is a function in the iostream library that allows you to seek an arbitrary position in a file. It is included in the <fstream> header file and is defined for istream class. It is used in file handling to sets the position of the next character to be extracted from the input stream from a given file. Syntax: There are two syntaxes for
3 min read
tellp() in file handling with c++ with example
The tellp() function is used with output streams, and returns the current "put" position of the pointer in the stream. It has no parameters and return a value of the member type pos_type, which is an integer data type representing the current position of the put stream pointer.Syntax: pos_type tellp(); Return - Current output position indicator on
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 Update Data in JSON File using JavaScript ?
JSON stands for JavaScript Object Notation. It is a text-based data exchange format that allows you to transfer data between different languages and platforms. JavaScript is commonly used to interact with JSON files. Updating data in a JSON file involves reading the file and then making the necessary changes to the JSON object and then writing the
4 min read
How to Fix <bits/stdc++.h> File not Found in MacOS?
The majority of the standard C++ headers can be easily included in your code with the #include<bits/stdc++.h> directive. It is not, however, a standard header file, and its availability on all systems or with all compilers is not assured. Mainly used on Unix-like platforms, such as macOS, it is supported by the GNU Compiler Collection (GCC) a
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
Article Tags :
Practice Tags :