使用Boost ptree解析std::string
Parse std::string with Boost ptree
我有这样的代码
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";
}
只会复制得更少。它不会导致不同的错误报告。
考虑在字符串中包含换行符,以便解析器报告行号。
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- std中有类似find_last_of的函数,而string中没有
- 使用 std::string () const 函数启动线程或未来
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何更改大小(std::string)
- std::string 的对象真的可以移动吗?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- 确切地说,如何解释 std::getline(stream, string) 函数在C++中填充的字符串
- C++:考虑C++ std::string 中双引号 (") 的字面含义,而不使用反斜杠 (\)
- 'int main(int, int, std::__cxx11::string, std::__cxx11::string)'只需要零或两个参数 [-Wmain]
- C++ 在列表和列表之间选择返回类型<<string>std::p air<string,string>>
- std::string, std::wstring and UTF8
- uan inplace replacement of std::string/std::wstring?
- #define Glib::string std:wstring
- 从 std::string & std::wstring 中获取 char 整数值
- BSTR转换为std::string(std::wstring),反之亦然