gpt4 book ai didi

c++ - 使用 boost json_parser 需要指导

转载 作者:行者123 更新时间:2023-11-28 02:34:08 26 4
gpt4 key购买 nike

我有一个 JSON 文件,如下所示:

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

我对如何改编 boost 文档中的 XML 5 分钟示例有点迷茫。

到目前为止,我已经了解了创建结构和一些基础知识:

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

但我不知道如何让 BOOST_FOREACH 等为我工作?

最佳答案

这是使用 c++11 的快速演示

Live On 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";
}

打印:

1   that
2 (`this` not found)

更新 c++03版本:

Live On 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";
}

打印相同

关于c++ - 使用 boost json_parser 需要指导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28118041/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com