How to convert a json object to a map with nlohmann::json? How to convert a json object to a map with nlohmann::json? json json

How to convert a json object to a map with nlohmann::json?


nlomann::json can convert Json objects to to most standard STL containers with get<typename BasicJsonType>() const

Example:

// Raw string to json typeauto j = R"({  "foo" :  {    "bar" : 1,    "baz" : 2  }})"_json;// find object and convert to mapstd::map<std::string, int> m = j.at("foo").get<std::map<std::string, int>>();std::cout << m.at("baz") << "\n";// 2


There is function get in class json.

Try something along these lines:

m = j.get<std::map <std::string, std::vector <int>>();

You might have to fiddle a bit with it to make it work precisely the way you want it to.


The only solution that I found is just to parse it manually.

    std::map<std::string, std::vector<int>> m = { {"a", {1, 2}}, {"b", {2, 3}} };    json j = m;    std::cout << j << std::endl;    auto v8 = j.get<std::map<std::string, json>>();    std::map<std::string, std::vector<int>> m_new;    for (auto &i : v8)    {        m_new[i.first] = i.second.get<std::vector<int>>();    }    for(auto &item : m_new){        std::cout << item.first << ": " ;        for(auto & k: item.second ){            std::cout << k << ",";        }        std::cout << std::endl;    }

If there is a better way I would appreciate a hint.