如何在 boost 属性 树中写入嵌套列表并将其转储为 json?
How to write nested list in boost property tree and dump it as json?
我想在 boost json 中使用嵌套列表。我想要的是这样的
{"matrix": [[0.0, 0.0], [0.0, 0.0]]}
中找不到嵌套列表大小写
文档中关于创建列表值的内容不是很详细,我已经尝试完成了,我们需要用空路径调用put
,用空路径调用push_back
int main() {
pt::ptree child_inner1;
pt::ptree child_inner2;
child_inner1.put("", 0.0);
child_inner2.put("", 0.0);
pt::ptree child;
child.push_back(std::make_pair("", child_inner1));
child.push_back(std::make_pair("", child_inner2));
pt::ptree sub;
sub.push_back(std::make_pair("", child));
sub.push_back(std::make_pair("", child));
pt::ptree tree;
tree.add_child("matrix", sub);
std::ostringstream oss;
pt::write_json(oss, tree);
std::cout << oss.str();
return 0;
}
代码有点难看。所以我建议使用其他 JSON 库来生成 JSON。由于您使用的是 boost,最新版本的 boost 已经有一个超快的 JSON 库,并且采用现代设计,这将是一个好的开始:https://www.boost.org/doc/libs/1_75_0/libs/json/doc/html/index.html
我想在 boost json 中使用嵌套列表。我想要的是这样的
{"matrix": [[0.0, 0.0], [0.0, 0.0]]}
中找不到嵌套列表大小写
文档中关于创建列表值的内容不是很详细,我已经尝试完成了,我们需要用空路径调用put
,用空路径调用push_back
int main() {
pt::ptree child_inner1;
pt::ptree child_inner2;
child_inner1.put("", 0.0);
child_inner2.put("", 0.0);
pt::ptree child;
child.push_back(std::make_pair("", child_inner1));
child.push_back(std::make_pair("", child_inner2));
pt::ptree sub;
sub.push_back(std::make_pair("", child));
sub.push_back(std::make_pair("", child));
pt::ptree tree;
tree.add_child("matrix", sub);
std::ostringstream oss;
pt::write_json(oss, tree);
std::cout << oss.str();
return 0;
}
代码有点难看。所以我建议使用其他 JSON 库来生成 JSON。由于您使用的是 boost,最新版本的 boost 已经有一个超快的 JSON 库,并且采用现代设计,这将是一个好的开始:https://www.boost.org/doc/libs/1_75_0/libs/json/doc/html/index.html