[英]Guidance needed on using boost json_parser
我有一個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的快速演示
#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)
#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";
}
打印相同
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.