使用Boost ptree解析std::string

Parse std::string with Boost ptree

本文关键字:string std 解析 Boost ptree 使用      更新时间:2023-10-16

我有这样的代码

std::string ss = "{ "item1" : 123, "item3" : 456, "item3" : 789 }";
// Read json.
ptree pt2;
std::istringstream is(ss);
read_json(is, pt2);
std::string item1= pt2.get<std::string>("item1");
std::string item2= pt2.get<std::string>("item2");
std::string item3= pt2.get<std::string>("item3"); 

我需要将JSON字符串解析为std::string如上所示,我试图在这里放入catch语句但实际错误只是<unspecified file>(1):

所以我假设read_json只是读取文件,而不是std::string,以什么方式可以解析这个std::string ?

您的示例从读取(如果您愿意,这是"类似于文件")。流已经用您的字符串填充了。你在解析字符串。你不能直接从字符串中解析。

你可以使用Boost Iostreams直接从源字符串中读取,而不需要复制:

Live On Coliru

#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>
namespace pt = boost::property_tree;
std::string ss = "{ "item1" : 123, "item2" : 456, "item3" : 789 }";
int main()
{
    // Read json.
    pt::ptree pt2;
    boost::iostreams::array_source as(&ss[0], ss.size());
    boost::iostreams::stream<boost::iostreams::array_source> is(as);
    pt::read_json(is, pt2);
    std::cout << "item1 = "" << pt2.get<std::string>("item1") << ""n";
    std::cout << "item2 = "" << pt2.get<std::string>("item2") << ""n";
    std::cout << "item3 = "" << pt2.get<std::string>("item3") << ""n";
}

只会复制得更少。它不会导致不同的错误报告。

考虑在字符串中包含换行符,以便解析器报告行号。