c++ - boost ptree 访问没有路径名的第一个元素

标签 c++ boost boost-propertytree

我正在使用 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:

Live On Coliru

#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/

相关文章:

c++ - stdafx.h 到头文件

c++ - SwisTrack - USB 摄像头黑色输入

c++ - 映射键是 C++ 中多个值的组合

c++ - 为什么定义模板类的 boost::shared_ptr 与非模板类的 boost::shared_ptr 行为不同

c++ - 使用 Boost 属性树将 Unicode 字符串写入 XML

c++ - 使用 boost::property_tree 读取 ini 文件不适用于表单 A.x 的子项

c++ - 在 C++ 中编码时无法在 VS Code 中使用 auto 关键字

c++ - 使用 <pcap.h> 手动生成数据包

boost - find_package(Boost) 返回空的 Boost_LIBRARIES

c++ - Boost C++ 属性 - 如果键不存在则设置为 false