问题
Here is the hello world of rapidjson. How can I change key "hello"
to "goodbye"
and get string from the json? I mean I want to parse json, change some keys and get json string back like {"goodbye" : "world"}
.
const char json[] = "{ \"hello\" : \"world\" }";
rapidjson::Document d;
d.Parse<0>(json);
回答1:
const char *json = R"({"hello": "world"})";
rapidjson::Document d;
d.Parse<0> (json);
rapidjson::Value::Member* hello = d.FindMember ("hello"); if (hello) {
d.AddMember ("goodbye", hello->value, d.GetAllocator());
d.RemoveMember ("hello");
}
typedef rapidjson::GenericStringBuffer<rapidjson::UTF8<>, rapidjson::MemoryPoolAllocator<>> StringBuffer;
StringBuffer buf (&d.GetAllocator());
rapidjson::Writer<StringBuffer> writer (buf, &d.GetAllocator());
d.Accept (writer);
json = buf.GetString();
P.S. You should probably copy the json
afterwards because its memory will be freed together with d
.
P.P.S. You can also replace the field name in-place, without removing it:
rapidjson::Value::Member* hello = d.FindMember ("hello");
if (hello) hello->name.SetString ("goodbye", d.GetAllocator());
Or during iteration:
for (auto it = d.MemberBegin(); it != d.MemberEnd(); ++it)
if (strcmp (it->name.GetString(), "hello") == 0) it->name.SetString ("goodbye", d.GetAllocator());
回答2:
In my case there is a key dictionary named keyDict
which stores the values that object keys should be replaced with.
std::string line;
std::map<std::string, int> keyDict;
.....................
.........................
rapidjson::Document doc;
doc.Parse<0>(line.c_str());
rapidjson::Value::MemberIterator itr;
for (itr = doc.MemberonBegin(); itr != doc.MemberonEnd(); ++itr)
{
std::string keyCode = std::to_string(keyDict[itr->name.GetString()]);
itr->name.SetString(keyCode.c_str(), keyCode.size(), doc.GetAllocator());
}
来源:https://stackoverflow.com/questions/24204417/rapidjson-change-key-to-another-value