Write in file using Rapidjson

user2815841 picture user2815841 · Feb 4, 2014 · Viewed 13.8k times · Source

How can i write some data into file using rapidjson document :

Here is what i need to write :

"Big Node ": [   
              {    "Big Key": "Key Value 1",    "Child Key": "Key Value 1",    "Values": [     1,     3,     4,     1,     2,     3    ]   },
              {    "Big Key": "Key Value 2",    "Child Key": "Key Value 2",    "Values": [     17,     18,     5,     4,     17]   }
             ]

Answer

ArtemGr picture ArtemGr · Apr 4, 2014

Once you get the string, writing it to a file is as easy as std::ofstream (path) << string.

Here's an example writing JSON to a file:

char cbuf[1024]; rapidjson::MemoryPoolAllocator<> allocator (cbuf, sizeof cbuf);
rapidjson::Document meta (&allocator, 256);
meta.SetObject();
meta.AddMember ("foo", 123, allocator);

typedef rapidjson::GenericStringBuffer<rapidjson::UTF8<>, rapidjson::MemoryPoolAllocator<>> StringBuffer;
StringBuffer buf (&allocator);
rapidjson::Writer<StringBuffer> writer (buf, &allocator);
meta.Accept (writer);
std::string json (buf.GetString(), buf.GetSize());

std::ofstream of ("/tmp/example.json");
of << json;
if (!of.good()) throw std::runtime_error ("Can't write the JSON string to the file!");

If you want to avoid the double-buffering then you can write directly to ofstream:

struct Stream {
  std::ofstream of {"/tmp/example.json"};
  typedef char Ch;
  void Put (Ch ch) {of.put (ch);}
  void Flush() {}
} stream;

rapidjson::Writer<Stream> writer (stream, &allocator);
meta.Accept (writer);

There's also FileWriteStream.