Search code examples
c++jsonxmlboostboost-propertytree

Checking if a path exists in a boost property tree


How do I check if a path exists in a property tree?

Example:

boost::property_tree::ptree tree;

// if path doesn't exist, put value
if (/*...*/)
{
    tree.put("my.path.to.thing", true);
}

Solution

  • For a simple solution, you can use get_optional()

    According to the documentation, if it exists, it returns the value otherwise it returns an uninitialized optional

    Example

    boost::property_tree::ptree tree;
    
    // if path doesn't exist, put value
    if (!tree.get_optional<bool>("my.path.to.thing").is_initialized())
    {
        tree.put("my.path.to.thing", true);
    }