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

use*_*020 5 c++ json dictionary nlohmann-json

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

map<string, vector<int>> m = { {"a", {1, 2}}, {"b", {2, 3}} };
json j = m;
Run Code Online (Sandbox Code Playgroud)

但我做不到

m = j;
Run Code Online (Sandbox Code Playgroud)

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

Fre*_*red 7

nlomann::json 可以将 Json 对象转换为大多数标准 STL 容器 get<typename BasicJsonType>() const

例子:

// 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
Run Code Online (Sandbox Code Playgroud)


Leh*_*ehu 4

getjson类中有函数。

尝试按照以下思路进行操作:

m = j.get<std::map <std::string, std::vector <int>>();
Run Code Online (Sandbox Code Playgroud)

您可能需要稍微摆弄它才能使其完全按照您想要的方式工作。