How to Read and Parse Json File with RapidJson?
Last Updated :
26 Apr, 2025
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 of how to parse a JSON file using RapidJSON.
Example 1:
C++
#include "rapidjson/document.h"
#include "rapidjson/filereadstream.h"
#include <cstdio>
int main()
{
// Open the file
FILE* fp = fopen("test.json", "rb");
// Read the file into a buffer
char readBuffer[65536];
rapidjson::FileReadStream is(fp, readBuffer,
sizeof(readBuffer));
// Parse the JSON document
rapidjson::Document doc;
doc.ParseStream(is);
// Close the file
fclose(fp);
// Use the data in the document
// ...
return 0;
}
This example reads the contents of a file called "test.json" into a buffer and then parses the JSON document using the ParseStream function. The parsed document is stored in a rapidjson::Document object, which provides access to the data in the JSON document. You can then access the data in the document using the various member functions of the rapidjson::Document class. For example, to access an object member, you can use the GetObject function, and to access an array member, you can use the GetArray function. You can also use the HasMember function to check if an object has a particular member, and the Size function to get the size of an array. Here is a more detailed example of how to parse a JSON file using RapidJSON, with explanations of each step:
Example 2:
C++
#include "rapidjson/document.h"
#include "rapidjson/filereadstream.h"
#include <cstdio>
#include <iostream>
int main()
{
// Open the file
FILE* fp = fopen("test.json", "rb");
// Check if the file was opened successfully
if (!fp) {
std::cerr << "Error: unable to open file"
<< std::endl;
return 1;
}
// Read the file into a buffer
char readBuffer[65536];
rapidjson::FileReadStream is(fp, readBuffer,
sizeof(readBuffer));
// Parse the JSON document
rapidjson::Document doc;
doc.ParseStream(is);
// Check if the document is valid
if (doc.HasParseError()) {
std::cerr << "Error: failed to parse JSON document"
<< std::endl;
fclose(fp);
return 1;
}
// Close the file
fclose(fp);
// Access the data in the document
// Suppose the JSON document has the following
// structure:
// {
// "name": "John Smith",
// "age": 30,
// "city": "New York",
// "skills": ["programming", "guitar", "singing"]
// }
// Get the "name" member
if (doc.HasMember("name") && doc["name"].IsString()) {
std::string name = doc["name"].GetString();
std::cout << "Name: " << name << std::endl;
}
// Get the "age" member
if (doc.HasMember("age") && doc["age"].IsInt()) {
int age = doc["age"].GetInt();
std::cout << "Age: " << age << std::endl;
}
// Get the "city" member
if (doc.HasMember("city") && doc["city"].IsString()) {
std::string city = doc["city"].GetString();
std::cout << "City: " << city << std::endl;
}
// Get the "skills" array
if (doc.HasMember("skills")
&& doc["skills"].IsArray()) {
const rapidjson::Value& skills = doc["skills"];
std::cout << "Skills: ";
for (rapidjson::SizeType i = 0; i < skills.Size();
i++) {
if (skills[i].IsString()) {
std::string skill = skills[i].GetString();
std::cout << skill << " ";
}
}
std::cout << std::endl;
}
return 0;
}
Sample test.json:
Â
Output:
Â
Explanation of Example:
In this example, we first open the file "test.json" using the fopen function. Then, we read the contents of the file into a buffer using the rapidjson::FileReadStream class. Parsing a JSON document means converting a JSON-formatted string into a JSON object that can be accessed and manipulated in your program. RapidJSON provides several functions for parsing JSON, including:
- Parse: parses a JSON string
- ParseInsitu: parses a JSON string in-place (i.e., without making a copy of the string)
- ParseStream: parses a JSON document from an input stream
Once a JSON document has been parsed, you can access the data in the document using the various member functions of the rapidjson::Document class. For example:
- IsObject: returns true if the document is an object
- IsArray: returns true if the document is an array
- IsString: returns true if the document is a string
- IsNumber: returns true if the document is a number (integer or floating-point)
- IsBool: returns true if the document is a boolean value
- GetObject: returns the object at the specified path within the document
- GetArray: returns the array at the specified path within the document
- GetString: returns the string at the specified path within the document
- GetInt: returns the integer at the specified path within the document
- GetUint: returns the unsigned integer at the specified path within the document
- GetInt64: returns the 64-bit integer at the specified path within the document
- GetUint64: returns the 64-bit unsigned integer at the specified path within the document
- GetDouble: returns the double-precision floating-point number at the specified path within the document
- GetBool: returns the boolean value at the specified path within the document
Here is an example of how to access data in a JSON document using these functions:
Example 3:
C++
#include "rapidjson/document.h"
int main()
{
// Parse the JSON document
rapidjson::Document doc;
doc.Parse("{\"name\":\"John\",\"age\":30,\"city\":"
"\"New York\"}");
// Access the data in the document
if (doc.IsObject()) {
// Get the "name" member
if (doc.HasMember("name")
&& doc["name"].IsString()) {
std::string name = doc["name"].GetString();
std::cout << "Name: " << name << std::endl;
// Output:- Name: John
}
// Get the "age" member
if (doc.HasMember("age") && doc["age"].IsInt()) {
int age = doc["age"].GetInt();
std::cout << "Age: " << age << std::endl;
// Output:- Age: 30
}
// Get the "city" member
if (doc.HasMember("city")
&& doc["city"].IsString()) {
std::string city = doc["city"].GetString();
std::cout << "City: " << city << std::endl;
// Output:- City: New York
}
}
return 0;
}
Output:
This code parses the JSON document contained in the string literal "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}" using the Parse() method of the rapidjson::Document object. The document is then accessed and the values of the "name", "age", and "city" members are extracted and printed to the console.
Â
Similar Reads
How to Read JSON Files with Pandas?
JSON (JavaScript Object Notation) store data using key-value pairs. Reading JSON files using Pandas is simple and helpful when you're working with data in .json format. There are mainly three methods to read Json file using Pandas Some of them are:Using pd.read_json() MethodUsing JSON Module and pd.
2 min read
How to read and write JSON files in Scala?
Scala is frequently used for reading and writing JSON files in a variety of applications, particularly it includes data transmission.Table of ContentSteps for reading JSON files in Scala:Steps for writing JSON files in Scala:Steps for reading JSON files in Scala:When reading JSON files in Scala we f
3 min read
How to read and write JSON file using Node ?
Node JS is a free and versatile runtime environment that allows the execution of JavaScript code outside of web browsers. It finds extensive usage in creating APIs and microservices, catering to the needs of both small startups and large enterprises.JSON(JavaScript Object Notation) is a simple and t
3 min read
How to Read Large JSON file in R
First, it is important to understand that JSON (JavaScript Object Notation), is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. JSON files are often used for data transmission between a server and a web application and can
6 min read
RapidJSON - File Read/Write in C++
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
6 min read
How to read/write JSON File?
Ruby is a dynamic, object-oriented programming language developed by Yukihiro Matsumoto in the mid-1990s. Its key features include a simple and elegant syntax, dynamic typing, object-oriented nature, support for mixins and modules, blocks and closures, metaprogramming, and a vibrant community with a
6 min read
How to read this JSON file with jsonlite in R?
JSON data is represented as key-value pairs, which are similar to the concept of a dictionary in Python or a list of named elements in R. In this article, we will learn how to access different components of a JSON file using R. What is jsonlite package in R? The jsonlite package in R provides an eas
2 min read
How to parse a JSON File in PHP?
We will explore how to parse a JSON file and display its data using PHP. PHP is a server-side scripting language commonly used to process and manipulate data. JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for both humans and machines to read and write. It st
3 min read
Read, Write and Parse JSON using Python
JSON is a lightweight data format for data interchange that can be easily read and written by humans, and easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called JSON. Example of JSON String s = '{"id":0
4 min read
Reading and Writing JSON to a File in Python
The full form of JSON is Javascript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Pytho
3 min read