Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 515
user1899020 Avatar asked Oct 14 '16 15:10

user1899020


1 Answers

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
like image 126
Fred Avatar answered Oct 17 '22 15:10

Fred