Parse a JSON array as std :: string with Boost ptree

I have this code that I need to parse / or get a JSON array as std :: string to be used in the application.

std::string ss = "{ \"id\" : \"123\", \"number\" : \"456\", \"stuff\" : [{ \"name\" : \"test\" }] }"; ptree pt2; std::istringstream is(ss); read_json(is, pt2); std::string id = pt2.get<std::string>("id"); std::string num= pt2.get<std::string>("number"); std::string stuff = pt2.get<std::string>("stuff"); 

It is necessary that the "material" be obtained in this way as std :: string [{ "name" : "test" }]

However, the code above stuff just returns an empty string. What could be wrong

+5
c ++ boost
source share
2 answers

Arrays are represented as child nodes with many "" keys:

docs

  • JSON arrays are mapped to nodes. Each element is a child node with an empty name. If a node has named and unnamed child nodes, it cannot be displayed in the JSON view.

Live on coliru

 #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> using boost::property_tree::ptree; int main() { std::string ss = "{ \"id\" : \"123\", \"number\" : \"456\", \"stuff\" : [{ \"name\" : \"test\" }, { \"name\" : \"some\" }, { \"name\" : \"stuffs\" }] }"; ptree pt; std::istringstream is(ss); read_json(is, pt); std::cout << "id: " << pt.get<std::string>("id") << "\n"; std::cout << "number: " << pt.get<std::string>("number") << "\n"; for (auto& e : pt.get_child("stuff")) { std::cout << "stuff name: " << e.second.get<std::string>("name") << "\n"; } } 

Print

 id: 123 number: 456 stuff name: test stuff name: some stuff name: stuffs 
+6
source share

Since "stuff" is an array, you can iterate over its elements, which are dictionaries. And then you can iterate over the dictionary elements, which are key-value pairs:

 for (const auto& dict : pt2.get_child("stuff")) { for (const auto& kv : dict.second) { std::cout << "key = " << kv.first << std::endl; std::cout << "val = " << kv.second.get_value<std::string>() << std::endl; } } 
0
source share

All Articles