SoFunction
Updated on 2025-03-10

C++ How to write files using RapidJson

Write files using RapidJson (C++)

Some of the contents of this article are generated by AI

Initially, I wanted to be able to write a level 3 json into the file using RapidJson. Its secondary level json is generated by for loop calculation. But after writing it over and over again, I found that there was a lot of garbled code, which seemed to be the reason why the string space was destroyed before it was written to the stream? (Unsure) So, the following example was generated using AI.

Write json files based on C++

#include <rapidjson/>
#include <rapidjson/>
#include <rapidjson/>
#include <rapidjson/> // for prettywriter
#include <rapidjson/>
#include <rapidjson/>
#include <cstdio>
using namespace rapidjson;
int main() {
    // Create a JSON object    Document d;
    ();
    Document::AllocatorType& allocator = ();
    ("name", Value().SetString("John Doe", allocator), allocator);
    ("age", 30, allocator);
    ("is_student", false, allocator);
    // Write to the file    FILE* fp = fopen("", "wb"); // Non-Windows platforms may need to use "w"    char writeBuffer[65536];
    FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));
    PrettyWriter<FileWriteStream> writer(os);   // Note that you can not use PrettyWriter, but the structure you write is not good-looking, Pretty will write json into a tree structure    (writer);
    fclose(fp);
    // Read the file    fp = fopen("", "rb"); // Non-Windows platforms may need to use "r"    char readBuffer[65536];
    FileReadStream is(fp, readBuffer, sizeof(readBuffer));
    Document d2;
    (is);
    fclose(fp);
    // Output the read content (simple example)    printf("Name: %s\n", d2["name"].GetString());
    printf("Age: %d\n", d2["age"].GetInt());
    printf("Is Student: %s\n", d2["is_student"].GetBool() ? "true" : "false");
    return 0;
}

Use RapidJson to write a file, which is written to a secondary json (including multiple objects)

#include <cstdio>
#include <rapidjson/>
#include <rapidjson/>
#include <rapidjson/>
#include <rapidjson/> // for PrettyWriter
#include <rapidjson/>
using namespace rapidjson;
int main() {
    // Create a JSON document, which will serve as our root object    Document document;
    ();
    Document::AllocatorType& allocator = ();
    // Create a JSON array    Value array(kArrayType);
    // Create the first object and add it to the array    Value object1(kObjectType);
    ("id", 1, allocator);
    ("name", "John Doe", allocator);
    (object1, allocator);
    // Create a second object and add it to the array    Value object2(kObjectType);
    ("id", 2, allocator);
    ("name", "Jane Smith", allocator);
    (object2, allocator);
    // Create a third object and add it to the array    Value object3(kObjectType);
    ("id", 3, allocator);
    ("name", "Alice Johnson", allocator);
    (object3, allocator);
    // Add array to root object    ("users", array, allocator);
    // Write JSON to file    FILE* fp = fopen("", "wb"); // Non-Windows platforms may need to use "w"    char writeBuffer[65536];
    FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));
    PrettyWriter<FileWriteStream> writer(os);
    (writer);
    fclose(fp);
    return 0;
}

Use RapidJson to write a secondary json file containing multiple objects, use a for loop

#include <cstdio>
#include <rapidjson/>
#include <rapidjson/>
#include <rapidjson/>
#include <rapidjson/> // for PrettyWriter
#include <rapidjson/>
using namespace rapidjson;
int main() {
    // Create a JSON document as the root object    Document document;
    ();
    Document::AllocatorType& allocator = ();
    // Create a JSON array    Value usersArray(kArrayType);
    // Use a for loop to generate multiple user objects    for (int i = 1; i <= 5; ++i) {
        Value userObject(kObjectType);
        // For the sake of simplicity of the example, i is used here as part of id and name        ("id", i, allocator);
        // Create a Value with a dynamic string        std::string name = "User " + std::to_string(i);
        Value nameValue;
        (name.c_str(), static_cast<SizeType>(()), allocator);
        ("name", nameValue, allocator);
        // Add user objects to array        (userObject, allocator);
    }
    // Add array to root object    ("users", usersArray, allocator);
    // Write to the file    FILE* fp = fopen("users_output.json", "wb"); // Non-Windows platforms may need to use "w"    char writeBuffer[65536];
    FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));
    PrettyWriter<FileWriteStream> writer(os);
    (writer);
    fclose(fp);
    return 0;
}

This code first creates a root JSON documentdocumentand an arrayusersArray. passforLoop, we create five user objects, each containingidandnamefield wherenameIt is by indexing the loopiConvert to a string and with"User "Connected to get. These user objects are added tousersArrayIn the end, this array is added to the root document and passedPrettyWriterWrite to the nameusers_output.jsonin the file.

result:

{
    "users": [
        {
            "id": 1,
            "name": "User 1"
        },
        {
            "id": 2,
            "name": "User 2"
        },
        {
            "id": 3,
            "name": "User 3"
        },
        {
            "id": 4,
            "name": "User 4"
        },
        {
            "id": 5,
            "name": "User 5"
        }
    ]
}

Use RapidJson to write a level 3 json to a file

#include <cstdio>
#include <string>
#include <rapidjson/>
#include <rapidjson/>
#include <rapidjson/>
using namespace rapidjson;
int main() {
    // Create root document    Document document;
    ();
    Document::AllocatorType& allocator = ();
    // Create a JSON array for storing department information    Value departmentsArray(kArrayType);
    // Use the for loop to add departments and employees    for (int depId = 1; depId <= 3; ++depId) {
        Value departmentObject(kObjectType);
        // Department ID and name        ("departmentId", depId, allocator);
        std::string depName = "Department " + std::to_string(depId);
        Value depNameValue;
        (depName.c_str(), allocator);
        ("name", depNameValue, allocator);
        // Create an array of employees for each department        Value employeesArray(kArrayType);
        for (int empId = 1; empId <= 4; ++empId) {
            Value employeeObject(kObjectType);
            ("employeeId", empId, allocator);
            std::string empName = "Employee " + std::to_string(empId) + " of Dep " + std::to_string(depId);
            Value empNameValue;
            (empName.c_str(), allocator);
            ("name", empNameValue, allocator);
            // Add employee objects to employee array            (employeeObject, allocator);
        }
        // Add employee array to department object        ("employees", employeesArray, allocator);
        // Add department objects to department array        (departmentObject, allocator);
    }
    // Add department array to root document    ("departments", departmentsArray, allocator);
    // Write to the file    FILE* fp = fopen("departments_output.json", "wb"); // Non-Windows platforms may need to use "w"    char writeBuffer[65536];
    FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));
    PrettyWriter<FileWriteStream> writer(os);
    (writer);
    fclose(fp);
    return 0;
}
  • We created a root document document that contains an array called departments.
  • Through the outer for loop, we create an object with basic information (ID and name) for each department and an array called employees for each department.
  • The inner for loop creates several employee objects for each department, each employee object containing the employee's ID and name.
  • Finally, each department object (including its employee array) is added to the department array, and the entire department array is eventually added to the root document and written to a file called departments_output.json via PrettyWriter.

result

{
    "departments": [
        {
            "departmentId": 1,
            "name": "Department 1",
            "employees": [
                {
                    "employeeId": 1,
                    "name": "Employee 1 of Dep 1"
                },
                {
                    "employeeId": 2,
                    "name": "Employee 2 of Dep 1"
                },
                {
                    "employeeId": 3,
                    "name": "Employee 3 of Dep 1"
                },
                {
                    "employeeId": 4,
                    "name": "Employee 4 of Dep 1"
                }
            ]
        },
        {
            "departmentId": 2,
            "name": "Department 2",
            "employees": [
                {
                    "employeeId": 1,
                    "name": "Employee 1 of Dep 2"
                },
                {
                    "employeeId": 2,
                    "name": "Employee 2 of Dep 2"
                },
                {
                    "employeeId": 3,
                    "name": "Employee 3 of Dep 2"
                },
                {
                    "employeeId": 4,
                    "name": "Employee 4 of Dep 2"
                }
            ]
        },
        {
            "departmentId": 3,
            "name": "Department 3",
            "employees": [
                {
                    "employeeId": 1,
                    "name": "Employee 1 of Dep 3"
                },
                {
                    "employeeId": 2,
                    "name": "Employee 2 of Dep 3"
                },
                {
                    "employeeId": 3,
                    "name": "Employee 3 of Dep 3"
                },
                {
                    "employeeId": 4,
                    "name": "Employee 4 of Dep 3"
                }
            ]
        }
    ]
}

This is the article about C++ writing files using RapidJson. For more related C++ writing files, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!