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
C++ Programming Language
C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Object Oriented Programming in C++
Object Oriented Programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th
5 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Backpropagation in Neural Network
Backpropagation is also known as "Backward Propagation of Errors" and it is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network. In this article we will explore what
10 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the informatio
10 min read
AVL Tree Data Structure
An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of
4 min read
What is Vacuum Circuit Breaker?
A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read