3

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

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
Tampa
  • 75,446
  • 119
  • 278
  • 425

2 Answers2

6
  // 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);
user928204
  • 230
  • 2
  • 6
  • Where in the docs does it say that `boost::optional v2 = pt.get_optional("test3");` is allowed even if the value type of `test3` is not a string? (I've searched but can't find it.) – Olumide Feb 10 '17 at 17:41
2

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.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100