I am new to json parsing with boost using the property tree.
If I have this hash:
foo = {'test1',true}
ptree pt;
bool v = pt.get<bool>("test2");
I need to check a key exists and if not set it to false.
How do I do that gracefully?
Thanks
I am new to json parsing with boost using the property tree.
If I have this hash:
foo = {'test1',true}
ptree pt;
bool v = pt.get<bool>("test2");
I need to check a key exists and if not set it to false.
How do I do that gracefully?
Thanks
// bool optional
boost::optional<bool> v = pt.get_optional<bool>("test2");
// any type actually
boost::optional<std::string> v2 = pt.get_optional<std::string>("test3");
if (v) // key exists
bool bool_value = v.get();
else // not exists
v.set(false);
From boost documentation you can try to find the key and if not_found()
then you can push a new key.
assoc_iterator not_found() ; Returns the not-found iterator. Equivalent to end() in a real associative container.
const_assoc_iterator not_found() const; Returns the not-found iterator. Equivalent to end() in a real associative container.
assoc_iterator find(const key_type & key) ; Find a child with the given key, or not_found() if there is none. There is no guarantee about which child is returned if multiple have the same key.
const_assoc_iterator find(const key_type & key) const; Find a child with the given key, or not_found() if there is none. There is no guarantee about which child is returned if multiple have the same key.