Boost c++ property - if key does not exist then set to false

Tampa picture Tampa · Feb 22, 2013 · Viewed 8.3k times · Source

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

Answer

user928204 picture user928204 · Feb 22, 2013
  // 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);