Reputation: 91
Hello I'm using boost library c++ to parse a json object having this form :
{ "ser" : ["ser1","ser2"] , "ver" : ["ver1","ver2"] }
using pt::read_json(jsonobj, config) and now I'm looking to store the different parsed json object parts ( key and value ) into a map of strings and a vector of strings .
any idea please ?
Upvotes: 1
Views: 965
Reputation: 393114
Big Warning: Property Tree is NOT a JSON library. It has large limitations.
That said, if all you wish is a map of (vectors of) strings, then this might be adequate for your needs.
Let's make a shorthand for the map type:
using VMap = std::map<std::string, std::vector<std::string> >;
Now, let's make function to transform from a property tree into that VMap:
VMap to_map(ptree const& pt) {
VMap m;
for (auto& [k, v] : pt) {
auto& m_entry = m[k];
for (auto& [k, v] : boost::make_iterator_range(v.equal_range(""))) {
m_entry.push_back(v.get_value<std::string>());
}
}
return m;
}
Adding a print
function we can demo it:
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <iostream>
#include <map>
using boost::property_tree::ptree;
using VMap = std::map<std::string, std::vector<std::string> >;
VMap to_map(ptree const&);
void print(VMap const&);
int main() {
ptree config;
{
std::istringstream jsonobj(R"({ "ser" : ["ser1","ser2"] , "ver" : ["ver1","ver2"] })");
read_json(jsonobj, config);
}
auto m = to_map(config);
print(m);
}
VMap to_map(ptree const& pt) {
VMap m;
for (auto& [k, v] : pt) {
auto& m_entry = m[k];
for (auto& [k, v] : boost::make_iterator_range(v.equal_range(""))) {
m_entry.push_back(v.get_value<std::string>());
}
}
return m;
}
void print(VMap const& vm) {
for (auto& [k, vv] : vm) {
std::cout << k << ": {";
for (auto& v: vv)
std::cout << " " << v;
std::cout << " }\n";
}
}
Prints
ser: { ser1 ser2 }
ver: { ver1 ver2 }
Upvotes: 1