C++用BOOST_FOREACH读取Boost.PropertyTree JSON数组抛出异常求助
报错根因
你遇到的boost::property_tree::ptree_bad_path异常是因为路径寻址和实际JSON结构不匹配:你定义的JSON中Class字段对应的值是数组类型,数组的每一个元素才包含Student节点,无法直接通过Class.Student路径直接定位到目标节点。
正确实现代码
#include <string> #include <iostream> #include <sstream> #include <boost/property_tree/json_parser.hpp> #include <boost/foreach.hpp> using namespace std; using boost::property_tree::ptree; int main() { const char* f_strSetting = R"({"Class": [{"Student": {"Name":"John","Course":"C++"}}]})"; boost::property_tree::ptree pt1; std::istringstream l_issJson(f_strSetting); boost::property_tree::read_json(l_issJson, pt1); // 第一层遍历Class对应的数组 BOOST_FOREACH(boost::property_tree::ptree::value_type & arrItem, pt1.get_child("Class")) { // 从数组元素中获取Student节点 ptree studentNode = arrItem.second.get_child("Student"); std::string l_strName = studentNode.get<std::string>("Name"); std::string l_strCourse = studentNode.get<std::string>("Course"); cout << l_strName << endl; cout << l_strCourse << endl; } return 0; }
修改点说明
- 新增
<sstream>头文件,补全std::istringstream的依赖声明 - 调整遍历逻辑:先遍历
Class对应的数组节点,拿到数组内的每一个元素 - 从数组元素中提取
Student节点后,再读取其下的Name、Course属性值 - 修正了原代码中换行符的错误写法,改为标准的
endl
内容的提问来源于stack exchange,提问作者sas。
相关产品推荐
相关产品推荐

