【问题标题】:How to convert a json object to a map with nlohmann::json?如何使用 nlohmann::json 将 json 对象转换为地图?
【发布时间】:2017-02-24 02:29:18
【问题描述】:

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

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

但我做不到

m = j;

有什么方法可以使用 nlohmann::json 将 json 对象转换为地图?

【问题讨论】:

  • 我建议您在下面投票并接受@Fred 的回答。 (如果你不坚持你的问题,你会被否决!)

标签: c++ json dictionary nlohmann-json


【解决方案1】:

nlomann::json 可以使用get&lt;typename BasicJsonType&gt;() 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

【讨论】:

    【解决方案2】:

    类json中有get函数。

    尝试以下方法:

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

    您可能需要稍微调整一下才能使其按照您想要的方式准确运行。

    【讨论】:

      【解决方案3】:

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

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

      如果有更好的方法,我将不胜感激。

      【讨论】:

      【解决方案4】:

      事实上,您的代码在当前版本 (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]}
      

      【讨论】:

      • 他在问反面:例如m = j;
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-08
      • 1970-01-01
      • 2023-01-19
      • 1970-01-01
      • 2017-07-29
      • 1970-01-01
      相关资源
      最近更新 更多