Quickjson - change the key to another value

Here is a world of greeting. How to change key "hello"to "goodbye"and get string from json? I want me to parse json, change some keys and return json string as {"goodbye" : "world"}.

const char json[] = "{ \"hello\" : \"world\" }";

rapidjson::Document d;
d.Parse<0>(json);
+4
source share
2 answers
  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();

PS Most likely you should copy json, because his memory will be freed with d.

PPS You can also replace the field name in place without deleting 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());
+8
source

In my case, there is a key dictionary with a name keyDictthat stores values ​​that should be replaced with object keys.

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());
}
+2
source

Source: https://habr.com/ru/post/1544465/


All Articles