Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

Accessing Deeply Nested Elements
PrevUpHomeNext

In order to allow conveniently retrieving and changing deeply nested elements of value objects the library implements RFC 6901 (JSON Pointer):

value jv = { {"one", 1}, {"two", 2} };
assert( jv.at("one") == jv.at_pointer("/one") );

jv.at_pointer("/one") = {{"foo", "bar"}};
assert( jv.at("one").at("foo") == jv.at_pointer("/one/foo") );

jv.at_pointer("/one/foo") = {true, 4, "qwerty"};
assert( jv.at("one").at("foo").at(1) == jv.at_pointer("/one/foo/1") );

This is particularly useful when throwing exceptions is undesirable. For example, compare

object* obj = jv.if_object();
if( !obj )
    return nullptr;

value* val = obj->if_contains("one");
if( !val )
    return nullptr;

obj = val->if_object();
if( !obj )
    return nullptr;

val = obj->if_contains("foo");
if( !val )
    return nullptr;

array* arr = val->if_array();
if( !arr )
    return nullptr;

return arr->if_contains(1);

with

error_code ec;
return jv.find_pointer("/one/foo/1", ec);

PrevUpHomeNext