Reputation: 982
Below are the steps I followed to fetch values from a JSON file:
{
"Bases":[
{
"mnemonic":"ADIS.LA.01",
"relay":true
},
{
"mnemonic":"ALEX.LA.01",
"relay":true
}
]
}
I am failing to fetch the boolean values.
In the code below, I am:
Code:
ReadJsonFile()
{
using boost::property_tree::ptree;
const boost::property_tree::ptree& propTree
boost::property_tree::read_json(ss, pt);
const std::string rootElement = "Bases";
boost::property_tree::ptree childTree;
bool m_relay;
try
{
/** get_child - Get the child at the given path, or throw @c ptree_bad_path. */
childTree = propTree.get_child(rootElement);
}
catch (boost::property_tree::ptree_bad_path& ex)
{
return false;
}
BOOST_FOREACH(const boost::property_tree::ptree::value_type &v, propTree.get_child(rootElement)){
string vID;
for (ptree::const_iterator subTreeIt = v.second.begin(); subTreeIt != v.second.end(); ++subTreeIt) {
if (subTreeIt->first == "mnemonic")
{
// Get the value string and trim the extra spaces, if any
vID = boost::algorithm::trim_copy( subTreeIt->second.data() );
}
if (subTreeIt->first == "relay")
{
m_relay = boost::algorithm::trim_copy(subTreeIt->second.data());
}
}
}
}
Error:
error: cannot convert ‘std::basic_string<char, std::char_traits<char>, std::allocator<char> >’ to ‘bool’ in assignment
Apparently the boolean value "relay":true
is treated as a string instead of a bool
.
If I change
bool m_relay;
to
std::string m_relay;
The code works fine, but the bool
type is failing to compile.
Am I missing something?
Upvotes: 1
Views: 3746
Reputation: 598011
Try using this:
m_relay = subTreeIt->second.get_value<bool>();
Instead of this:
m_relay = boost::algorithm::trim_copy(subTreeIt->second.data());
Upvotes: 1
Reputation: 16090
You have to cast it manually:
boost::lexical_cast<bool>(subTreeIt->second.data());
But it doesn't seem like a preferred way. I urge you to read Docs: How to Access Data in a Property Tree.
However, I don't see another way using an iterator. So I guess you are fine, given that you already have it. The preferred ways seem to hinge on the path, which you do not use.
For what it's worth... You probably should use find
instead of iterating manually, or refactor your code for some version of get
. It seems like a better design.
Upvotes: 0