c++jsonboostboost-propertytree

Unhandled exception when trying to retrieve the value from the JSON ptree using Boost C++


I am getting the below error when reading the value from the JSON ptree using Boost C++

Unhandled exception at 0x7682B502 in JSONSampleApp.exe: Microsoft C++ exception : 
boost::wrapexcept<boost::property_tree::ptree_bad_path> at memory location 0x00DFEB38.

Below is the program, Could someone please help me what i am missing here.

#include <string>
#include <iostream>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/foreach.hpp>

using namespace std;

using boost::property_tree::ptree;

int main()
{
    const char* f_strSetting = "{\"Student\": {\"Name\":\"John\",\"Course\":\"C++\"}}";

    boost::property_tree::ptree pt1;
    std::istringstream l_issJson(f_strSetting);
    boost::property_tree::read_json(l_issJson, pt1);

    BOOST_FOREACH(boost::property_tree::ptree::value_type & v, pt1.get_child("Student"))
    {
        std::string l_strColor;
        std::string l_strPattern;
        l_strColor = v.second.get <std::string>("Name");
        l_strPattern = v.second.get <std::string>("Course");
    }
    return 0;
}

Solution

  • There is a shape mismatch between your code and your data:

    Either fix the code:

    // Drop the BOOST_FOREACH
    auto & l_Student = pt1.get_child("Student");
    l_strColor = l_Student.get<std::string>("Name");
    

    or fix the data:

    // Note the extra []
    const char * f_strSetting = R"({"Student": [{"Name":"John","Course":"C++"}]})";