-
Notifications
You must be signed in to change notification settings - Fork 2
The DataTree object
Plaristote edited this page Sep 14, 2017
·
1 revision
The DataTree
object is the root of a boost' propety_tree
. Through the DataTree
object, you can generate Data
objects which provide tools to access and edit the tree's contents.
The root branch itself can be accessed as a Data
object by using the as_data()
method:
DataTree datatree;
Data root = datatree.as_data();
The DataTree::operator[]
method returns an object of type Data
. The Data
object provides several methods to access the content of a DataTree
:
Data user_data = datatree["user"];
std::string firstname, lastname;
std::vector<std::string> friends;
unsigned short age;
if (user_data["firstname"].exists())
firstname = user_data["firstname"].as<std::string>();
if (user_data["lastname"].is_blank())
throw "user.lastname is an empty string";
if (user_data["friends"].is_array())
friends = user_data["friends"].to_vector<std::string>();
age = user_data["age"].defaults_to<unsigned short>(21);
It also provides methods to store content in the DataTree
:
Data user_data = datatree["user"];
// storing values with the operator= overload
user_data["firstname"] = "Luc";
user_data["age"] = 50;
// storing arrays with the from_vector method
std::vector<std::string> friends = { "roger", "robert", "bernard" };
user_data["friends"].from_vector<std::string>(friends);
You may load a DataTree
directly from a json string, stringstream, or by loading a file. Here are a few examples:
DataTree json_file;
// From a string
json_file.from_json("{ \"user\": { \"lastname\": \"Dupuis\" } }");
std::cout << "User's lastname: " << json_file["user"]["lastname"].as<std::string>() << std::endl;
json_file.clear(); // The clear method resets the DataTree
// From a file
json_file.from_json_file("/tmp/some_file.json");
std::cout << "File content: " << json_file.to_json() << std::endl;