Trying to create JSONs on the fly for my application, but the JSON I recieve does not remain constant.
std::string ResponseJson::getValue(std::string filter, std::string filterName, std::string jsonIndex)
{
BOOST_FOREACH(boost::property_tree::ptree::value_type & arrayElement, root.get_child("message"))
{
std::string value = arrayElement.second.get<std::string>(filter);
if (value == filterName)
{
return arrayElement.second.get<std::string>(jsonIndex);
}
}
return "";
}
above code snippet works well but message is the child which can be changed in different jsons so how can I make this function generic ?
Related
we are facing an issue where the RAPIDJSON_ASSERT(IsObject()) called by MemberEnd() which is called by HasMember() fails. However, that rapidjson::Value is guaranteed to be an object by other logic.
Here is the code snippet:
const std::string str = "{\"outer_key\":{\"inner_key\":\"value\", \"foo\":\"bar\"}}";
rapidjson::Document doc;
if (doc.Parse(str.c_str()).HasParseError()) {
return -1;
}
rapidjson::Value::MemberIterator it = doc.FindMember("outer_key");
// make sure the member is of Object type
if (it == doc.MemberEnd() || !it->value.IsObject()) {
return -1;
}
rapidjson::Value* p_json;
p_json = &(it->value);
rapidjson::Document new_doc;
rapidjson::Document::AllocatorType& new_doc_allocator = new_doc.GetAllocator();
// if SOME_FLAG is set and "outer_key" exists in the input JSON string,
// use "outer_key"'s value so that `new_doc` will have other properties such as `foo` for free.
if (SOME_FLAG && p_json != NULL) {
new_doc.CopyFrom(*p_json, new_doc_allocator);
// The value of "inner_key" will be re-added later, so remove it for now.
// assert(IsObject()) fails here and core is dumped.
if (new_doc.HasMember("inner_key")) {
new_doc.RemoveMember("inner_key");
}
} else {
// Otherwise, start from an empty object.
new_doc.SetObject();
}
// Add "inner_key" for both cases above.
const std::string new_value_str = "new_value";
new_doc.AddMember("inner_key", rapidjson::StringRef(new_value_str.c_str()), new_doc_allocator);
We suspect that the new_doc.CopyFrom(*p_json, new_doc_allocator); line is the culprit, but are kind of new to rapidjson and not sure whether it is the correct way to use new_doc_allocator to copy *p_json to new_doc.
The weird part is that this issue only happened online for a small number of requests. We extracted the input JSON string, checked that it is valid, but couldn't reproduce the failure offline.
It would be good if someone could point out where we did wrong. Thanks in advance.
When handling XML attributes in C++, how should different operations be run for different attributes?
Currently, I have something like this:
// get list of attributes for an XML element into member called 'attributes'
// ...
// run appropriate functions for each attribute
for (auto attribute : attributes)
{
auto name = attribute.name;
auto value = attribute.value;
if (name == "x")
doSomethingWithX(value);
else if (name == "y")
doSomethingWithY(value);
}
For just a few attribute names, this isn't so bad - but with a larger number (>15) this starts to look messy and I'm concerned about performance issues.
What might be a better way of handling XML attributes like this?
You can use a std::unordererd_map<std::string, std::function<void (const std::string&)>> and set it up with appropriate lambda functions:
std::unordererd_map<std::string, std::function<void (const std::string&)>> attrProcessors = {
{ "X", [](const std::string& value) {
// Do something with value
} } } ,
{ "Y", [](const std::string& value) {
// Do something with value
} } }
};
// run appropriate functions for each attribute
for (auto attribute : attributes)
{
auto name = attribute.name;
auto value = attribute.value;
auto processorEntry = attrProcessors.find(name);
if(processorEntry != attrProcessors.end()) {
(*processorEntry).second(value);
}
}
I am not so sure though that maintenace of the map entries would be easier to read than the if / else if cascade.
On the other hand you won't need to create an extra function for each attribute name.
I'm having some trouble with the following method and I need some help trying to figure out what I am doing wrong.
I want to return a reference to a Value in a document. I am passing the Document from outside the function so that when I read a json file into it I don't "lose it".
const rapidjson::Value& CTestManager::GetOperations(rapidjson::Document& document)
{
const Value Null(kObjectType);
if (m_Tests.empty())
return Null;
if (m_current > m_Tests.size() - 1)
return Null;
Test& the_test = m_Tests[m_current];
CMyFile fp(the_test.file.c_str()); // non-Windows use "r"
if (!fp.is_open())
return Null;
u32 operations_count = 0;
CFileBuffer json(fp);
FileReadStream is(fp.native_handle(), json, json.size());
if (document.ParseInsitu<kParseCommentsFlag>(json).HasParseError())
{
(...)
}
else
{
if (!document.IsObject())
{
(...)
}
else
{
auto tests = document.FindMember("td_tests");
if (tests != document.MemberEnd())
{
for (SizeType i = 0; i < tests->value.Size(); i++)
{
const Value& test = tests->value[i];
if (test["id"].GetInt() == the_test.id)
{
auto it = test.FindMember("operations");
if (it != test.MemberEnd())
{
//return it->value; is this legitimate?
return test["operations"];
}
return Null;
}
}
}
}
}
return Null;
}
Which I am calling like this:
Document document;
auto operations = TestManager().GetOperations(document);
When I inspect the value of test["operations"] inside the function I can see everything I would expect (debug code removed from the abode code).
When I inspect the returned value outside the function I can see that it's an array (which I expect). the member count int the array is correct as well, but when print it out, I only see garbage instead.
When I "print" the Value to a string inside the methods, I get what I expect (i.e. a well formated json), but when I do it outside all keys show up as "IIIIIIII" and values that aren't strings show up correctly.
rapidjson::StringBuffer strbuf2;
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer2(strbuf2);
ops->Accept(writer2);
As this didn't work I decided to change the method to receive a Value as a parameter and do a deep copy into it like this
u32 CTestManager::GetOperationsEx(rapidjson::Document& document, rapidjson::Value& operations)
{
(...)
if (document.ParseInsitu<kParseCommentsFlag>(json).HasParseError())
{
(...)
}
else
{
if (!document.IsObject())
{
(...)
}
else
{
auto tests = document.FindMember("tests");
if (tests != document.MemberEnd())
{
for (SizeType i = 0; i < tests->value.Size(); i++)
{
const Value& test = tests->value[i];
if (test["id"].GetInt() == the_test.id)
{
const Value& opv = test["operations"];
Document::AllocatorType& allocator = document.GetAllocator();
operations.CopyFrom(opv, allocator); //would Swap work?
return operations.Size();
}
}
}
}
}
return 0;
}
Which I'm calling like this:
Document document;
Value operations(kObjectType);
u32 count = TestManager().GetOperationsEx(document, operations);
But... I get same thing!!!!
I know that it's going to be something silly but I can't put my hands on it!
Any ideas?
The problem in this case lies with the use of ParseInSitu. When any of the GetOperations exist the CFileBuffer loses scope and is cleaned up. Because the json is being parsed in-situ when the buffer to the file goes, so goes the data.
For example,
I'm building a json message using following code:
json11::Json my_json = json11::Json::object{
{ "key_val1", val1},
{ "key_val2", val2},
{ "key_val3", val3},
{ "key_val4", val4 }
};
std::string message = my_json.dump();
But if i want to have this json11 object contain different attribute-value pair based on some condition then I've to repeat the same code multiple times.
Is there any way to append attribute-value pair to an existing json11 object?
So that i can build a base object and then append necessary attributes on demand.
Yes it's possible.
json11::Json::object my_json = json11::Json::object{
{ "key_val1", val1},
{ "key_val2", val2},
{ "key_val3", val3},
{ "key_val4", val4 }
};
my_json["newattribute1"] = "newValue1";
my_json["newattribute2"] = 2;
json11::Json json_final = json11::Json{ my_json };
std::string message = json_final .dump();
In your case my_json is an instance of json11::Json. In my case my_json is an instance of json11::Json::object.
json11::Json::object is originally a std::map.
I am using jsoncpp to read settings from a JSON file.
I would like to have two cascading settings file, say MasterSettings.json and LocalSettings.json where LocalSettings is a subset of MasterSettings. I would like to load MasterSettings first and then LocalSettings. Where LocalSettings has a value that differs from MasterSettings, that value would overwrite the one from MasterSettings. Much like the cascade in CSS.
Is there any elegant way to do this with jsoncpp?
I'm going to assume your settings files are JSON objects.
As seen here, when JSONCpp parses a file, it clears the contents of the root node. This mean that trying to parse a new file on top of the old one won't preserve the old data. However, if you parse both files into separate Json::Value nodes, it's straight forward to recursively copy the values yourself by iterating over the keys in the second object using getMemberNames.
// Recursively copy the values of b into a. Both a and b must be objects.
void update(Json::Value& a, Json::Value& b) {
if (!a.isObject() || !b.isObject()) return;
for (const auto& key : b.getMemberNames()) {
if (a[key].isObject()) {
update(a[key], b[key]);
} else {
a[key] = b[key];
}
}
}
I know it has been a while. but...
In addition to the correct answer and the commentary, here is a code version for those who use a older g++ version:
void jsonMerge(Json::Value &a, Json::Value &b) {
if (!a.isObject() || !b.isObject()) return;
vector<string> member_name = b.getMemberNames();
string key = "";
for (unsigned i = 0, len = member_name.size(); i < len; i++) {
key = member_name[i];
if (!a[key].isNull() && a[key].type() == Json::objectValue && b[key].type() == Json::objectValue) {
jsonMerge(a[key], b[key]);
} else {
a[key] = b[key];
}
}
member_name.clear();
}