I am working on a C++ project and I use rapidjson
for JSON parsing. I have this JSON:
{
"a": "valA",
"b": {
"ba": "valBA",
"bb": "valBB",
"bc": "valBC"
},
"c": "valC"
}
I parse the whole JSON and I get a Document
object containing all values. What I want is to somehow process this Document
object and extract only the b
part. As if I was parsing this JSON:
{
"b": {
"ba": "valBA",
"bb": "valBB",
"bc": "valBC"
}
}
I thought of parsing the Document
object myself but I was wondering if there is an easier/faster way of doing that. Any ideas?
"b" element can be extracted and put into a new document this way:
#include <iostream>
#include <rapidjson/document.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>
using namespace rapidjson;
int main(void)
{
const char* json = "{\"a\": \"valA\",\"b\": {\"ba\": \"valBA\",\"bb\": \"valBB\",\"bc\": \"valBC\"},\"c\": \"valC\"}";
Document d;
d.Parse<0>(json);
Value& data = d["b"];
Document d2;
d2.SetObject();
d2.AddMember("b", data, d2.GetAllocator());
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d2.Accept(writer);
std::cout << buffer.GetString() << std::endl;
return 0;
}
Output:
{"b":{"ba":"valBA","bb":"valBB","bc":"valBC"}}