c++ - Access to specific index in ptree array -
i using boost library manipulate json file , access specific index of array in json.
boost::property_tree::ptree& jsonfile; const boost::property_tree::ptree& array = jsonfile.get_child("my_array");
what accessing value stored @ index :
// code not compile int value = array[index].get < int > ("property");
just code using iterators:
template <typename t = std::string> t element_at(ptree const& pt, std::string name, size_t n) { return std::next(pt.get_child(name).find(""), n)->second.get_value<t>(); }
if want have index checked bounds:
template <typename t = std::string> t element_at_checked(ptree const& pt, std::string name, size_t n) { auto r = pt.get_child(name).equal_range(""); (; r.first != r.second && n; --n) ++r.first; if (n || r.first==r.second) throw std::range_error("index out of bounds"); return r.first->second.get_value<t>(); }
demo
#include <boost/property_tree/json_parser.hpp> #include <iostream> using boost::property_tree::ptree; template <typename t = std::string> t element_at(ptree const& pt, std::string name, size_t n) { return std::next(pt.get_child(name).find(""), n)->second.get_value<t>(); } template <typename t = std::string> t element_at_checked(ptree const& pt, std::string name, size_t n) { auto r = pt.get_child(name).equal_range(""); (; r.first != r.second && n; --n) ++r.first; if (n || r.first==r.second) throw std::range_error("index out of bounds"); return r.first->second.get_value<t>(); } int main() { ptree pt; { std::istringstream iss("{\"a\":[1, 2, 3, 4, 5, 6]}"); read_json(iss, pt); } write_json(std::cout, pt, false); // 4th element: std::cout << element_at_checked(pt, "a", 3) << "\n"; // int std::cout << element_at_checked<int>(pt, "a", 3) << "\n"; // non-existent array: try { std::cout << element_at_checked<int>(pt, "b", 0) << "\n"; } catch(std::exception const& e) { std::cout << e.what() << "\n"; } try { std::cout << element_at_checked<int>(pt, "a", 6) << "\n"; } catch(std::exception const& e) { std::cout << e.what() << "\n"; } }
prints
{"a":["1","2","3","4","5","6"]} 4 4 no such node (b) index out of bounds
Comments
Post a Comment