c++ - 使用 Boost 将 JSON 数组值解析为 std::string

标签 c++ boost

我正在尝试使用以下代码解析 std::string JSON 字符串:

        std::string ss = "{ \"id\" : \"abc123\", \"number\" : \"0123456789\", \"somelist\" : [{ \"timestamp\" : \"May 1, 2015\" , \"data\" : { \"description\" : \"some description\", \"value\" : \"100.000000\" } }] }";

        ptree pt2;
        std::istringstream is(ss);
        read_json(is, pt2);
        std::string _id = pt2.get<std::string>("id");
        std::string _number = pt2.get<std::string>("number");
        std::string _list = pt2.get<std::string>("somelist"); 


        for (auto& e : pt2.get_child("somelist")) {
            std::cout << "timestamp: " << e.second.get<std::string>("timestamp") << "\n";
            for (auto& e1 : pt2.get_child("data")){ // not working
                std::cout << "description: " << e1.second.get<std::string>("description") << "\n";
                std::cout << "value: " << e1.second.get<std::string>("amount") << "\n";
            }
        }

尽管我的目标不是打印子项(也不是将 JSON 字符串转换为 C++ 数组)。上面的代码不起作用。

我想知道如何获取 data 的值,而不是数组或其他东西,就像这样的字符串 [{ "timestamp": "May 1, 2015", "data ": { "description": "some description", "value": "100.000000"} }]

只需要 JSON 数组作为 std::string

最佳答案

boost/property_tree/json_parser.hpp 实现了 write_json,如您所料,它是 read_json 的逆函数。由于 ptree 将数组存储为具有空键的对象,为了实现您想要的表示,您将遍历 pt2.get_child( “somelist”),对它们中的每一个调用 write_json 并根据需要格式化这些表示。

for(auto const& node : pt2.get_child("somelist"))
 write_json(std::cout, node.second);

Coliru Demo .

关于c++ - 使用 Boost 将 JSON 数组值解析为 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31349039/

相关文章:

c++ - Boost.Graph 库:如何使用 boost::is_isomorphism 命名顶点

c++ - 在 C++03 中将 std::string 移动到 boost::thread

c++ - 具有更多模板参数的部分特化

C++/boost : Undefined Symbols in example?

c++ - Boost python,暴露迈耶斯单例

c++ - Thrust+boost代码编译错误

c++ - 重置对源文件更改的检测

c++ - 制作一个简单的 C++ 键盘记录器

c++ - 删除指针后将其设为 NULL 是一个好习惯吗?

c++ - boost static_vector 而不是 std::is_trivially_destructible