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

user1899020 picture user1899020 · Oct 14, 2016 · Viewed 9.5k times · Source

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?

Answer

Fred picture Fred · Oct 11, 2017

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