I am trying to write a function that should check whether a member exists on a document. If it does it should remove the member and re-add it with a different value.
This is what I got so far (d is a rapidjson::Document
):
void addMemberWithoutDuplication(std::string member, rapidjson::Value val) {
if (d.HasMember(member)) {
d.RemoveMember(member);
}
d.AddMember(rapidjson::StringRef(member), val, allocator);
}
This compiles and runs however the output is not as expected:
As shown rapidjson::StringRef(member)
seems to be the cause of the question marks inside the boxes.
Reading these pages of the docs did not help me a lot:
https://rapidjson.org/structrapidjson_1_1_generic_string_ref.html
https://rapidjson.org/classrapidjson_1_1_generic_object.html
From what I read I should be doing it correctly but most likely my inexperience reading these types of docs is an issue here. Does anyone know what I am doing wrong or am missing?
I eventually found an answer in this post: https://github.com/Tencent/rapidjson/issues/261
When using a dynamic reference, a copy of the string should be stored in a rapidjson::Value
.
This makes the code as follows:
void addMemberWithoutDuplication(std::string member, rapidjson::Value val) {
if (d.HasMember(member)) {
d.RemoveMember(member);
}
rapidjson::Value key(member.c_str(), allocator);
d.AddMember(key, val, allocator);
}