c++jsonrapidjson

writing json using rapid json library removes all indention


I am using rapid json https://rapidjson.org/ for reading a json file and writing it to another one using a cpp on windows application using visual studio 2017.

File Reading Code

FILE* fp = fopen(inputJson, "rb"); // non-Windows use "r" 
char readBuffer[65536];
FileReadStream is(fp, readBuffer, sizeof(readBuffer));
Document d;
d.ParseStream(is);
fclose(fp);

std::string json_str(readBuffer);

File Writing Code

FILE* fp2 = fopen(outputJson, "wb"); // non-Windows use "w" 
char writeBuffer[65536];
FileWriteStream os(fp2, writeBuffer, sizeof(writeBuffer));
Writer<FileWriteStream> writer(os);
d.Accept(writer);
fclose(fp2);

But in the destination file the indention is all lost.

Source file

{
    "name" : "test_rapid",
    "rect_obj": 
    [
        {   "name": "high school mathematics",
            "price": 12,
            "fg_color": 
            {
                "input_type": "val_map_c",
                "input": 
                {   
                    "measname": "MetaData_eOrigin_c",
                    "values":  [0],
                    "mapping": ["white"],
                    "out_of_range" : "white"
                }
            }
        },

In destination file the indentions is lost

{"name":"test_rapid","rect_obj":[{"name":"high school mathematics","price":12,"fg_color":{"input_type":"val_map_c","input":{

How to maintain the indention?


Solution

  • To keep the indentation, you need to use PrettyWriter instead of Writer:

    FILE* fp2 = fopen(outputJson, "wb"); 
    char writeBuffer[65536];
    FileWriteStream os(fp2, writeBuffer, sizeof(writeBuffer));
    PrettyWriter<FileWriteStream> writer(os);
    writer.SetIndent(' ', 4);  // indent with 4 spaces
    d.Accept(writer);
    fclose(fp2);