1

我正在创建一个利用 boostptree库的 JSON 字符串,但我发现仅通过执行以下操作就很乏味。我需要向 ptree 添加一个简单的"metric.name" : [A, B]数组metrics。我能做得比这更好吗?或者至少以更简洁的方式写这个。

      pt::ptree metric_avg;
      metric_avg.put("", 9999);
      pt::ptree metric_std;
      metric_std.put("", 0);
      pt::ptree metric_distr;
      metric_distr.push_back({"", metric_avg});
      metric_distr.push_back({"", metric_std});
      metrics.add_child(metric.name, metric_distr);
4

2 回答 2

2

我会写一些辅助函数

template<typename T>
pt::ptree scalar(const T & value)
{
    pt::ptree tree;
    tree.put("", value);
    return tree;
}

template<typename T>
pt::ptree array(std::initialiser_list<T> container)
{
    pt::ptree tree;
    for (auto & v : container)
    { 
        tree.push_back(scalar(v));
    }
    return tree;
}

这样你就可以写

metrics.put(metric.name, array({ 9999, 0 }));
于 2021-01-28T13:55:27.410 回答
1

我会:

住在科利鲁

ptree metric_avg;
auto& arr = metric_avg.put_child("metric name", {});
arr.push_back({"", ptree("9999")});
arr.push_back({"", ptree("0")});

住在科利鲁

for (auto el : {"9999", "0"})
    arr.push_back({"", ptree(el)});

甚至住在 Coliru

for (auto el : {9999, 0})
    arr.push_back({"", ptree(std::to_string(el))});

所有这些打印

{
    "metric name": [
        "9999",
        "0"
    ]
}

另请参阅使用 Boost::Ptree 的 JSON 数组

于 2021-01-29T00:40:11.083 回答