gpt4 book ai didi

c++ - 使用 Boost ptree 解析 std::string

转载 作者:太空狗 更新时间:2023-10-29 23:14:55 25 4
gpt4 key购买 nike

我有这个代码

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

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

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

关于c++ - 使用 Boost ptree 解析 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31338148/

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