7

Following rapidjson documentation I'm able to generate a pretty-printed JSON ouput writting in a key-by-key approach, e.g.:

rapidjson::StringBuffer s;
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(s);    

writer.StartObject();
writer.Key("hello");
writer.String("world");
writer.EndObject();

std::string result = s.GetString();

However, I would like to do the same but using a JSON string (i.e. a std::string object which content is a valid JSON) to feed the writer, instead of calling Key(), String() and so.

Looking to the PrettyWriter API I don't see any method to pass a JSON string in that way. An alternative would be to pass the parsed JSON string as a rapidjson::Document object, but I haven't found that possibility.

Any idea about how this could be done, please?

fgalan
  • 11,732
  • 9
  • 46
  • 89
  • 1
    There is now a [`RawValue` function](http://rapidjson.org/classrapidjson_1_1_pretty_writer.html#a3136e3426a5d06e5da50f6e6aab8a5be) on the `Writer` interface which *would* accomplish this, but unfortunately it currently (rapidjson 1.1.0) does not work reliably with `PrettyWriter`. – ComicSansMS Mar 11 '17 at 19:12

1 Answers1

13

This is from their documentation:

// rapidjson/example/simpledom/simpledom.cpp`
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <iostream>

using namespace rapidjson;

int main() {
    // 1. Parse a JSON string into DOM.
    const char* json = "{\"project\":\"rapidjson\",\"stars\":10}";
    Document d;
    d.Parse(json);

    // 2. Modify it by DOM.
    Value& s = d["stars"];
    s.SetInt(s.GetInt() + 1);

    // 3. Stringify the DOM
    StringBuffer buffer;
    Writer<StringBuffer> writer(buffer);
    d.Accept(writer);

    // Output {"project":"rapidjson","stars":11}
    std::cout << buffer.GetString() << std::endl;
    return 0;
}

I assume you require #3?

  • 4
    Correction: you'll need to actually use PrettyPrint for the output to be formatted for readability (don't forget to include its header `#include `): `PrettyWriter writer(buffer);` – Daniel Sposito Apr 14 '22 at 04:56