我正在使用 boost 库来操作 JSON 字符串,我想访问第一个元素。
我想知道是否有一些方便的方法可以访问没有路径名的 ptree 的第一个元素。
我这样做了,但我没有得到任何值(value):
namespace pt = boost::property_tree;
pt::ptree pt2;
string json = "\"ok\"";
istringstream is(json);
try
{
pt::read_json(is, pt2);
cout << pt2.get_child("").equal_range("").first->first.data() << endl;
}
catch (std::exception const& e)
{
cerr << e.what() << endl;
}
解决方案:
替换cout << pt2.get_child("").equal_range("").first->first.data() << endl;
作者 cout << pt2.get_value<std::string>() << endl;
最佳答案
首先,属性树不是 JSON 库。
其次,输入不在库支持的 JSON 子集中 (e.g.)。
第三,由于输入的结果是一棵没有子节点的树,因此您应该使用根节点本身的值。
最后,如果您想要第一个节点,请使用ordered_begin()->second
:
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <iostream>
void broken_input() {
boost::property_tree::ptree pt;
std::istringstream is("\"ok\"");
read_json(is, pt);
std::cout << "Root value is " << pt.get_value<std::string>() << std::endl;
}
void normal_tree() {
boost::property_tree::ptree pt;
pt.put("first", "hello");
pt.put("second", "world");
pt.put("third", "bye");
std::cout << pt.ordered_begin()->second.get_value<std::string>() << std::endl;
write_json(std::cout, pt);
}
int main() {
try {
broken_input();
normal_tree();
}
catch (std::exception const& e)
{
std::cerr << e.what() << std::endl;
}
}
打印
Root value is ok
hello
{
"first": "hello",
"second": "world",
"third": "bye"
}
关于c++ - boost ptree 访问没有路径名的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49462690/