如何使用nlohmann :: json将json对象转换为地图?

时间:2016-10-14 15:28:29

标签: c++ json dictionary nlohmann-json

例如,使用nlohmann :: json,我可以做到

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

但我做不到

m = j;

用nlohmann :: json转换json对象到地图的任何方法?

4 个答案:

答案 0 :(得分:2)

我找到的唯一解决方案就是手动解析它。

    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;
    }

如果有更好的方法,我会很感激。

答案 1 :(得分:1)

json类中有函数get

尝试以下几点:

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

您可能需要对其进行一些操作才能使其按照您希望的方式正常工作。

答案 2 :(得分:1)

nlomann :: json可以使用get<typename BasicJsonType>() const

将Json对象转换为大多数标准STL容器

示例:

// 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 :(得分:0)

实际上,您的代码对当前版本(2.0.9)完全有效。

我试过了:

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

并获得输出

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