I'm trying to parse a std::string JSON string with this code:
std::string ss = "{ \"id\" : \"abc123\", \"number\" : \"0123456789\", \"somelist\" : [{ \"timestamp\" : \"May 1, 2015\" , \"data\" : { \"description\" : \"some description\", \"value\" : \"100.000000\" } }] }";
ptree pt2;
std::istringstream is(ss);
read_json(is, pt2);
std::string _id = pt2.get<std::string>("id");
std::string _number = pt2.get<std::string>("number");
std::string _list = pt2.get<std::string>("somelist");
for (auto& e : pt2.get_child("somelist")) {
std::cout << "timestamp: " << e.second.get<std::string>("timestamp") << "\n";
for (auto& e1 : pt2.get_child("data")){ // not working
std::cout << "description: " << e1.second.get<std::string>("description") << "\n";
std::cout << "value: " << e1.second.get<std::string>("amount") << "\n";
}
}
Although my target is not to print the child items (nor convert the JSON string into C++ array). The code above does not work.
I want to know how to get the value of data not as array or something, just as string like this [{ "timestamp" : "May 1, 2015" , "data" : { "description" : "some description", "value" : "100.000000" } }]
Just need the JSON Array as-is as std::string
std::stringstream ss; write_json(ss, pt2.get_child("data"));? In your case,.get_child("somelist").get_child("data")ore.get_child("data").. depending where in your code you want to use it.ptree d = e.second.get_child("data"); std::stringstream s1; write_json(s1, d); std::cout <<s1.str << std::endl;. Demo Link