RapidJSON - File Read/Write in C++
Last Updated :
24 Apr, 2025
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
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
6 min read
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
5 min read
How to Read and Write the Files in Golang?
Golang offers a vast inbuilt library that can be used to perform read and write operations on files. In order to read from files on the local system, the io/ioutil module is put to use. The io/ioutil module is also used to write content to the file. This revised version reflects the changes made in
4 min read
Interact with files in Python
Python too supports file handling and allows users to handle files i.e., to read, write, create, delete and move files, along with many other file handling options, to operate on files. The concept of file handling has stretched over various other languages, but the implementation is either complica
6 min read
I/O Redirection in C++
In C++, input and output operations are done in the form of sequence of bytes called stream through the stream objects like cin and cout. These objects use different components such as buffers, streams, etc. to efficiently read and write data to standard input and output devices such as keyboard and
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 tha
6 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
3 min read
ReadWriteLock Interface in Java
A lock is a device for commanding access to an assigned resource by multiple threads. Usually, a lock grants exclusive access to a shared resource: just one thread at a flash can acquire the lock and everyone accesses to the shared resource requires that the lock be acquired first. Though, some lock
3 min read
File Handling in Objective-C
File handling is an essential part of any programming language, and Objective C is no exception. It allows developers to create, read, update, and delete files on the file system. This can be useful for a wide range of applications such as storing user data, saving game progress, or logging applicat
9 min read
basic_istream::readsome() in C++ with Examples
The basic_istream::readsome() used to read the data from the buffer and extracts up to n immediately available characters from the input string. This function returns the number of extracted characters. Below is the syntax for the same: Header File: #include<iostream> Syntax: streamsize readso
2 min read