Open In App

RapidJSON – File Read/Write in C++

Improve
Improve
Like Article
Like
Save
Share
Report

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());



Last Updated : 23 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads