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:
- Opening the JSON file
- Setting the root element and start traversing the childtree under this root element (Bases)
- Fetching the values of each tag and saving them to appropriate variable types.
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?
Try using this:
Instead of this: