Reputation: 35276
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
Upvotes: 0
Views: 1171
Reputation: 16737
boost/property_tree/json_parser.hpp
implements write_json
, which is, as you would expect, the inverse of read_json
. Since ptree
stores arrays as objects with an empty key, to achieve the representation you want, you would loop over the top-level ptree
s in pt2.get_child("somelist")
, call write_json
on each of them and format these representations as you wish.
for(auto const& node : pt2.get_child("somelist"))
write_json(std::cout, node.second);
Upvotes: 1