1

I am trying to create json using rapidjson::Writer without creating document but it just give json text but don't create full json output like below,

{ "data": { "dataIn": { "hello":"world", "t":true, "f":false }, "dataOut": { "n":null, "i":123, "pi":3.1416 } } }

On rapidjson documents as well not enough info given. Can please help with it. How I can achieve this?

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60

1 Answers1

0

On rapidjson documents as well not enough info given. Can please help with it. How I can achieve this? - That is not true if I correctly understood your intentions.
At RapidJSON:Sax look for paragraph Writer - example given there is almost the same as the one you're asking for.
I wrote It myself to check if it is working .. and it is:

#include <iostream>
#include <rapidjson/writer.h>

// {
//     "data": 
//     {  
//         "dataIn": 
//         { 
//             "hello":"world", 
//             "t":true, 
//             "f":false 
//         }, 
//         "dataOut": 
//         { 
//             "n":null, 
//             "i":123, 
//             "pi":3.1416 
//         } 
//     } 
// }


int main(int argc, char** argv)
{
    rapidjson::StringBuffer lStringBuffer;
    rapidjson::Writer lWriter(lStringBuffer);

    lWriter.StartObject();
    lWriter.Key("data");
        lWriter.StartObject();
        lWriter.Key("dataIn");
            lWriter.StartObject();
            lWriter.Key("hello");
            lWriter.String("world");
            lWriter.Key("t");
            lWriter.Bool(true);
            lWriter.Key("f");
            lWriter.Bool(false);
            lWriter.EndObject();
        lWriter.Key("dataOut");
            lWriter.StartObject();
            lWriter.Key("n");
            lWriter.Null();
            lWriter.Key("i");
            lWriter.Int(123);
            lWriter.Key("pi");
            lWriter.Double(3.1416);
            lWriter.EndObject();
        lWriter.EndObject();
    lWriter.EndObject();

    std::cout << lStringBuffer.GetString() << std::endl;

    return 0;
}

The output is:

{"data":{"dataIn":{"hello":"world","t":true,"f":false},"dataOut":{"n":null,"i":123,"pi":3.1416}}}

But if you want to get such a JSON string you might also use raw strings like:

    std::string lRawString = R"(
    { 
        "data": 
        { 
            "dataIn": 
            { 
                "hello":"world",
                "t":true, "f":false 
            }, 
            "dataOut": 
            { 
                "n":null,
                "i":123,
                "pi":3.1416 
            } 
        } 
    }
    )";

and then pass it to rapidjson::Document:

rapidjson::Document lDocument;
lDocument.Parse(lRawString.c_str());
TenerowiczS
  • 147
  • 6