问题
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?
回答1:
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?
来源:https://stackoverflow.com/questions/40833243/rapidjson-pretty-print-using-json-string-as-input-to-the-writer