Using boost::json::value
, how do I check if a certain key exists?
The following code:
void checkMessage(std::string msg)
{
boost::json::value json = boost::json::parse(payload);
auto type = json.at("type").as_string();
auto param1 = json.at("param1").as_string();
auto param1 = json.at("param2").as_int64(); <<=== IT CHASHES HERE
std::cout << "Received: " << std::endl;
std::cout << "type: " << type << std::endl;
std::cout << "param1: " << param1 << std::endl;
std::cout << "param2: " << param2 << std::endl;
}
Crashes when trying to get the param2
from my json data:
terminate called after throwing an instance of 'boost::wrapexcept<std::out_of_range>'
what(): out of range
Aborted (core dumped)
When the param2
is missing:
std::string msg = "{\"type\", \"t1\", \"param1\": \"test parameter 1\"}";
Is there a way to check if the parameter exists before copying the json key value to the variable?
Is there a better way to do it?
As the commented suggested you can catch the
out of range
error (system_error exception).Or you can be more cautious and check first:
Likewise you can be more cautious about the string interpretation too:
Live On Coliru
Printing