简体   繁体   English

使用boost json_parser所需的指导

[英]Guidance needed on using boost json_parser

I've got a JSON file that looks like: 我有一个JSON文件,看起来像:

[{"id":"1","this":"that"},{"id":"2","that":"this"}]

I'm a bit lost in how to adapt the XML 5 minute example from the boost docs. 我对如何改编Boost文档中的XML 5分钟示例感到迷茫。

So far I've got as far as creating a struct and a couple of basics: 到目前为止,我已经创建了一个结构和一些基础知识:

struct sheet {
 int id;
 std::string info;
}
using boost::property_tree::ptree;
ptree pt;
read_json(filename, pt);

But I've no idea how to get BOOST_FOREACH etc. to work for me ? 但是我不知道如何让BOOST_FOREACH等为我工作?

Here's quick demo using c++11 这是使用c ++ 11的快速演示

Live On Coliru 生活在Coliru

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <sstream>
#include <iostream>

static std::string const sample = R"([{"id":"1","this":"that"},{"id":"2","that":"this"}])";

int main() {
    using namespace boost::property_tree;

    ptree pt;
    struct sheet { int id; std::string info; };

    std::istringstream iss(sample);
    read_json(iss, pt);

    std::vector<sheet> sheets;
    for(auto& e : pt)
    {
        std::string info = "(`this` not found)";

        auto this_property = e.second.get_child_optional("this");
        if (this_property)
            info = this_property->get_value(info);

        sheets.push_back(sheet {
            e.second.get_child("id").get_value(-1),
            info
        });
    }

    for(auto s : sheets)
        std::cout << s.id << "\t" << s.info << "\n";
}

Prints: 印刷品:

1   that
2   (`this` not found)

Update c++03 version: 更新 c ++ 03版本:

Live On Coliru 生活在Coliru

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <sstream>
#include <iostream>
#include <boost/foreach.hpp>

struct sheet { int id; std::string info; };
static std::string const sample = "[{\"id\":\"1\",\"this\":\"that\"},{\"id\":\"2\",\"that\":\"this\"}]";

int main() {
    using namespace boost::property_tree;

    ptree pt;
    std::istringstream iss(sample);
    read_json(iss, pt);

    std::vector<sheet> sheets;
    BOOST_FOREACH(ptree::value_type e, pt)
    {
        std::string info = "(`this` not found)";

        boost::optional<ptree&> this_property = e.second.get_child_optional("this");
        if (this_property)
            info = this_property->get_value(info);

        sheet s;

        s.id   = e.second.get_child("id").get_value(-1);
        s.info = info;

        sheets.push_back(s);
    }

    BOOST_FOREACH(sheet s, sheets)
        std::cout << s.id << "\t" << s.info << "\n";
}

Prints the same 打印相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM