访问ptree数组中的特定索引

时间:2017-08-18 09:45:38

标签: c++ boost ptree

我正在使用boost库来操作JSON文件,我想访问此JSON中的数组的特定索引。

boost::property_tree::ptree& jsonfile;
const boost::property_tree::ptree& array =
  jsonfile.get_child("my_array");

我想要做的是访问存储在index:

的值
// This code does not compile
int value = array[index].get < int > ("property");

1 个答案:

答案 0 :(得分:2)

使用迭代器进行编码:

function myFunction2()
    {
     var marks= 10;
}

如果要检查边界的索引:

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>();
}

演示

<强> Live On Coliru

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("");

    for (; 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>();
}

打印

#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("");

    for (; 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);

    // get the 4th element:
    std::cout << element_at_checked(pt, "a", 3) << "\n";

    // get it as int
    std::cout << element_at_checked<int>(pt, "a", 3) << "\n";

    // get 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"; }
}