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

筅森魡賤 提交于 2019-12-11 02:12:16

问题


For example, with nlohmann::json, I can do

map<string, vector<int>> m = { {"a", {1, 2}}, {"b", {2, 3}} };
json j = m;

But I cannot do

m = j;

Any way to convert a json object to a map with nlohmann::json?


回答1:


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.




回答2:


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

Example:

// Raw string to json type
auto j = R"(
{
  "foo" :
  {
    "bar" : 1,
    "baz" : 2
  }
}
)"_json;

// find object and convert to map
std::map<std::string, int> m = j.at("foo").get<std::map<std::string, int>>();
std::cout << m.at("baz") << "\n";
// 2



回答3:


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.




回答4:


In fact, your code is perfectly valid with the current version (2.0.9).

I tried:

std::map<std::string, std::vector<int>> m = { {"a", {1, 2}}, {"b", {2, 3}} };
json j = m;
std::cout << j << std::endl;

and got the output

{"a":[1,2],"b":[2,3]}


来源:https://stackoverflow.com/questions/40046853/how-to-convert-a-json-object-to-a-map-with-nlohmannjson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!